c# – 控制器构造函数中的Web API读取头值

前端之家收集整理的这篇文章主要介绍了c# – 控制器构造函数中的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.超过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>";
        }
    }
}

猜你在找的C#相关文章