C# 检索Web API C中客户端标头中包含的用户令牌#

C# 检索Web API C中客户端标头中包含的用户令牌#,c#,asp.net,api,C#,Asp.net,Api,我在web API中使用实体框架和JWT令牌生成器。 每个控制器都进行[授权],以防止未经授权的api调用。 因此,当客户端调用api时,它会发送一个包含令牌的头,以便进行评估。 有没有可能读取此令牌的方法?它包含有关公司用户值的信息,这对于定义正确的数据库是必要的 [Authorize] [ApiController] public class MyClass: ControllerBase { private readonly IMessageRepository dB;

我在web API中使用实体框架和JWT令牌生成器。 每个控制器都进行[授权],以防止未经授权的api调用。 因此,当客户端调用api时,它会发送一个包含令牌的头,以便进行评估。 有没有可能读取此令牌的方法?它包含有关公司用户值的信息,这对于定义正确的数据库是必要的

[Authorize]
[ApiController]
public class MyClass: ControllerBase
{
    private readonly IMessageRepository dB;

   
    public MyClassController(IMessageRepository messageRepository)
    {
        this.dB = messageRepository;
    // something to retrieve header here.
      
    }

    /// <summary>
    /// Return the list of X contained in the DB
    /// </summary>
   
    [HttpGet(ApiRoutes.MyRoute)]
    public List<Object> Get()
    {
        var x = dB.Get();
        return x;
    }
[授权]
[ApiController]
公共类MyClass:ControllerBase
{
专用只读IMessageRepository数据库;
公共MyClassController(IMessageRepository messageRepository)
{
this.dB=messageRepository;
//这里有一些要检索的标题。
}
/// 
///返回数据库中包含的X的列表
/// 
[HttpGet(apirouts.MyRoute)]
公共列表Get()
{
var x=dB.Get();
返回x;
}

我不知道这是否可行,但应该在构造函数中而不是在Api方法中检索头。

我从您的问题中了解到的是,您说Authorize属性在操作方法命中之前命中,它会自动决定此调用是否需要进入操作方法,并且您希望捕获该调用

因此,我的朋友,Mvc中有一些动作过滤器,它们调用动作方法之前和之后,并且“授权过滤器”总是在我遇到这个问题时在你的动作方法之前运行,在那个时候,我使用自定义属性来捕获内容

该类继承自“AuthorizeAttribute”,并且[Authorize]派生自“AuthorizationFilterAttribute”抽象类,因此我们在这里进行某种意义上的重写

您可以根据自己的使用方式进行更多定制

也许这会帮到你

 public class CustomAuthorize : AuthorizeAttribute
    {
        public string Permissionname { get; set; }
         public CustomAuthorize (string PermissionName)
        {
            Permissionname = PermissionName;
        }
        protected override bool IsAuthorized(HttpActionContext actionContext)
        {
            ClaimsIdentity claimsIdentity = HttpContext.Current.User.Identity as ClaimsIdentity;
            var _roles = claimsIdentity.FindAll(ClaimTypes.Role).ToList();
            bool isAuthorized = false;
            if (Permissionname!= "" && Permissionname != "AuthorizeOnly")
            {
                foreach (var item in _roles)
                {
                    if (item != null && item.Value != null && item.Value.ToLower() == Permissionname.ToLower())
                    {
                        isAuthorized = base.IsAuthorized(actionContext);
                    }
                }
            }
            else
            {
                isAuthorized = base.IsAuthorized(actionContext);
            }
            return isAuthorized;
        }
        protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
                //Setting error message and status Code 403 for unauthorized user
                actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)
                {
                    Content = new StringContent(JsonConvert.SerializeObject(new { Message = "Authorization failed or user don't have permission!" })),
                    StatusCode = HttpStatusCode.Forbidden
                };

        }
    }
你可以在你的行动方法上这样打电话

CustomAuthorize("CanViewLeads")]
Public HttpResponseMessage ActionMethodXYZ()
{
}


“应在构造函数中检索标头”这是没有意义的。构造函数不处理HTTP请求,方法是这样做的。它在处理任何传入请求之前被实例化。在方法中接收它有什么不对?或者如果你需要在很多方法中重用的话,考虑一个动作过滤器。在方法中使用它?非常感谢!关于如何检索头值,前面已经有很多问题,例如(以及更多)