【问题标题】:Web Api 2,Claims always null in my inheritance ApicontrollerWeb Api 2,在我的继承 Apicontroller 中声明始终为空
【发布时间】:2023-03-20 18:28:02
【问题描述】:

我在我的项目中使用 Web Api 2 Auth 模板。我想在客户端使用 Api Key 请求时获取用户 ID。我的问题是:

1 如何获取 api 客户端用户 ID。

-是对还是错通过Api请求解决?

-还是直接取http头中的userId?

-或者使用Api键从数据库中查询?

2 我创建了继承自 ApiController 的 MyApiController,我想在其中获取声明。所以我在其中编写了一些代码。像这样

protected override void Initialize(HttpControllerContext controllerContext)
   { 
    base.Initialize(controllerContext);
    var principal = Request.GetRequestContext().Principal as ClaimsPrincipal;
    CorpId = (from c in principal.Claims where c.Type.Contains("CorpId") select c.Value).FirstOrDefault();
    UserId = (from c in principal.Claims where c.Type.Contains("UserId") select c.Value).FirstOrDefault();
   }

我发现 MyApiController 中的声明为空。但是当我在动作控制器中这样做时,它有效吗?

【问题讨论】:

  • 你解决了吗?我也有同样的问题

标签: api web oauth asp.net-web-api2


【解决方案1】:

您宁愿在执行请求时(即在 Controller.Get 方法中)获取特定于请求的数据,而不是在创建控制器时。或者,如果控制器方法中不需要值,则使用过滤器属性。

【讨论】:

    猜你喜欢
    • 2016-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-03
    • 2013-01-15
    • 1970-01-01
    • 2014-07-07
    相关资源
    最近更新 更多