Read API API Header Value in Controller Constructor

Can I get the header information in the constructor of the web API controller? I want to set variables based on the value of the header, but I do not want to do this for each method. I am particularly interested in the custom value of the header, but I would agree to authorization at this point. I can get it to work in 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 } } 
+6
source share
1 answer

Below are some options you can consider ... prefer 1. over 2.

  • Save additional data in the current request for message properties HttpRequestMessage.Properties and get the convenience property in the 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 can get the current controller 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>"; } } } 
+11
source

Source: https://habr.com/ru/post/970271/


All Articles