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
    }
}
                Following are some options that you can consider...prefer 1. over 2.
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>";
    }
}
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>";
        }
    }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With