【问题标题】:Web API: Action Filter gets ClientId given ApiKey, but how to get ClientID in Controller classes?Web API:Action Filter 获取给定 ApiKey 的 ClientId,但如何在 Controller 类中获取 ClientID?
【发布时间】:2014-07-10 22:25:51
【问题描述】:

我有一个 Web API 服务,它通过请求标头传入 ApiKey。从 ActionFilterAttribute 派生的自定义操作过滤器 (AuthenticationRequiredAttribute) 会覆盖 OnActionExecuting 方法并执行 DB 调用以获取与有效 ApiKey 关联的 ClientId。我可以通过HttpActionContext.Request.Properties.Add ("clientID", clientID) 将ClientID 分配为属性,但是我无法在控制器操作方法中访问关联的actionContext 对象,因此它没有任何价值。

当然这是一种常见的情况,但我找不到一个很好的例子来处理它。如何将 HttpActionContext 实例放入控制器类中?

这是过滤器:

public override void OnActionExecuting(HttpActionContext actionContext)

在其中,我得到了 ClientID,但我看不到如何将它传递给下面的方法:

这是Controller的方法:

[Route("v1/stock/{SecurityId}/text")]
public HttpResponseMessage GetSummaryTextV1(string SecurityId, string topic = "")

HttpActionContext 在其中不可用。我这里需要ClientID,但是拿不到。

有没有办法可以将当前的 actionContext 传递给 Controller 构造函数?

不知所措,暂时硬连线 clientId,这样我就可以继续了。

【问题讨论】:

    标签: asp.net-web-api


    【解决方案1】:

    见:http://stevescodingblog.co.uk/basic-authentication-with-asp-net-webapi/

    我已经实现了这种方法。调用者通过身份验证后,我将其客户端 ID 存储在自定义 IIdentity 中,然后在控制器中使用。

    【讨论】:

      【解决方案2】:

      使用Request.Properties 访问属性。

      编辑:

      您可以像在问题中一样在属性中设置 ClientID

      HttpActionContext.Request.Properties.Add ("clientID", clientID)
      

      并使用Request.Properties 访问控制器中的属性

      【讨论】:

      • 嗨 - 我不知道这是否回答了这个问题(这不是我的专业知识),但这个答案很短,所以它最终出现在“低质量帖子”上审查队列。也许您可以对此提供更多解释,以便我们可以告诉任何一种方式?
      • 充其量只是答案的一半
      【解决方案3】:

      我找到了解决这个问题的简单方法。而不是使用从 ActionFilterAttribute 类派生并在 global.asax 中指定的自定义“AuthenticationRequired”属性:

      GlobalConfiguration.Configuration.Filters.Add(new AuthenticationRequiredAttribute());
      
      public class AuthenticationRequiredAttribute : ActionFilterAttribute
      {
          public override void OnActionExecuting(HttpActionContext actionContext)
          {
              /* My authentication and lookup logic here */
          }
      }
      

      我只是将逻辑放在一个新的 Controller 构造函数中,其中包含在成功验证时填充其值的字段。它简单明了。没有 HttpActionContext.Request.Properties.Add gobbledygook,没有复活会话对象,只有字段和构造函数。呃。话虽如此,我很欣赏我收到的两个建议;我只是无法实现它们。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-09-22
        • 1970-01-01
        • 2013-04-15
        • 2014-04-28
        • 2015-04-22
        • 1970-01-01
        • 2011-11-01
        相关资源
        最近更新 更多