Web API读取控制器构造函数中的标头值

时间:2014-06-03 20:24:32

标签: c# asp.net-web-api

是否可以获取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 个答案:

答案 0 :(得分:11)

以下是您可以考虑的一些选项...更喜欢1.而不是2.

  1. 将其他数据存储在当前请求消息的属性包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>";
        }
    }
    
  2. 您可以获取当前控制器的实例并设置属性值。例如:

    [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>";
            }
        }
    }