【问题标题】:Access object created in AuthenticationFilter from the Web API Controller从 Web API 控制器在 AuthenticationFilter 中创建的访问对象
【发布时间】:2015-07-01 12:21:50
【问题描述】:

我在 Web API 2 项目中实现了 HMAC 身份验证过滤器(根据 this article)。本文使用静态密钥进行演示,因此我修改了过滤器以使用“AppId”Guid 从数据库中查找私有 API 密钥。这很好用,因为我能够为该 AppId 条目加载适当的帐户。但我想知道是否可以访问在我的控制器的身份验证过滤器类中创建的“帐户”对象。

这就是我声明对象的方式:

public class HMACAuthenticationAttribute : Attribute, IAuthenticationFilter
    {
        private static Dictionary<string, string> allowedApps = new Dictionary<string, string>();
        public DummyAccount account = new DummyAccount();
    }

然后在代码中:

// Load account and its private API Key
                    account = accountService.GetByAppId(Guid.Parse(appId), session);

                    if (account == null)
                    {
                        context.ErrorResult = new UnauthorizedResult(new AuthenticationHeaderValue[0], context.Request);
                    }

                    // If we find the account, we add to allowedApps the AppId/PrivateKey pair
                    allowedApps.Add(account.AppId.ToString(), account.ApiKey);

现在在我的 WebApi 控制器中,代码如下所示:

        [HMACAuthentication]
        [HttpPost]
        public RatingDto Post(SearchTrackDto searchedTrack)
        {

            // Access 'account' object here?

        }

我的期望是我可以以某种方式直接访问帐户对象,这样我就不必再次解析请求并进行第二次数据库查询。将对象存储在 Request.Context 是要走的路吗?有什么选择?

【问题讨论】:

    标签: c# asp.net-web-api2 actionfilterattribute


    【解决方案1】:

    您可以尝试实现缓存。 AuthenticationFilter 应该验证每个请求,因为上下文生命周期范围是只要请求死亡。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-06
      相关资源
      最近更新 更多