Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web API read header value in controller constructor

Is it possible to get at the header information in the constructor of a web API controller? I want to set variables based off a header value but I don't want to have to do it for each method. I'm particularly interested in a custom header value but I would settle for the Authorization one at this point. I can get it to work in an AuthorizationFilterAttribute but I also need it at the controller level.

[PolicyAuthorize]
public class PoliciesController : ApiController
{
    public PoliciesController()
    {
        var x = HttpContext.Current;  //will be null in constructor
    }

    public HttpResponseMessage Get()
    {
        var x = HttpContext.Current;  //will be available but too late
    }
}

public class PolicyAuthorizeAttribute : AuthorizationFilterAttribute
{
    public override void OnAuthorization(HttpActionContext actionContext)
    {
        var authHeader = actionContext.Request.Headers.Authorization;  //can get at Authorization header here but no HTTPActionContext in controller
    }
}
like image 291
Curtis Avatar asked Jun 03 '14 20:06

Curtis


1 Answers

Following are some options that you can consider...prefer 1. over 2.

  1. Store additional data in current request message's properties bag HttpRequestMessage.Properties and have a convenience property in controller which all actions in the controller can access.

    [CustomAuthFilter]
    public class ValuesController : ApiController
    {
        public string Name
        {
            get
            {
                return Request.Properties["Name"].ToString();
            }
        }
    
        public string GetAll()
        {
            return this.Name;
        }
    }
    
    public class CustomAuthFilter : AuthorizationFilterAttribute
    {
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            actionContext.Request.Properties["Name"] = "<your value from header>";
        }
    }
    
  2. You could get the current controller's instance and set the property value. Example:

    [CustomAuthFilter]
    public class ValuesController : ApiController
    {
        public string Name { get; set; }
    
        public string GetAll()
        {
            return this.Name;
        }
    }
    
    public class CustomAuthFilter : AuthorizationFilterAttribute
    {
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            ValuesController valuesCntlr = actionContext.ControllerContext.Controller as ValuesController;
    
            if (valuesCntlr != null)
            {
                valuesCntlr.Name = "<your value from header>";
            }
        }
    }
    
like image 180
Kiran Avatar answered Nov 02 '22 07:11

Kiran