1

我在我的项目中使用 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 中的声明为空。但是当我在动作控制器中这样做时,它有效吗?

4

1 回答 1

0

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

于 2014-12-28T22:04:55.447 回答