gpt4 book ai didi

c# - Web API 在 Controller 构造函数中读取 header 值

转载 作者:太空狗 更新时间:2023-10-29 18:20:05 57 4
gpt4 key购买 nike

是否可以在 Web API Controller 的构造函数中获取 header 信息?我想根据 header 值设置变量,但我不想为每种方法都这样做。我对自定义 header 值特别感兴趣,但此时我会接受授权值。我可以让它在 AuthorizationFilterAttribute 中工作,但我也需要它在 Controller 级别。

[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.

  1. 在当前请求消息的属性包 HttpRequestMessage.Properties 中存储额外的数据,并在 Controller 中有一个方便的属性, Controller 中的所有操作都可以访问该属性。

    [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. 您可以获得当前 Controller 的实例并设置属性值。示例:

    [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# - Web API 在 Controller 构造函数中读取 header 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24024291/

57 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com