是否可以获取Web API控制器的构造函数中的头信息?我想根据标头值设置变量,但我不想对每个方法都这样做.我对自定义标头值特别感兴趣,但此时我会满足授权标准.我可以让它在AuthorizationFilterAttribute中工作,但我也需要它在控制器级别.
[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 } }
解决方法
以下是您可以考虑的一些选项…更喜欢1.超过2.
>将其他数据存储在当前请求消息的属性包HttpRequestMessage.Properties中,并在控制器中具有一个便利属性,控制器中的所有操作都可以访问该属性.
[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>"; } }
[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>"; } } }