使用 ASP.New MVC 4 Web Api 进行授权过滤器依赖注入

2024-04-16

我正在尝试在 MVC 4 Web Api 授权过滤器上实现依赖项注入。我创建了一个继承自 ActionDescriptorFilterProvider 的 FilterProvider:

public class UnityWebApiFilterAttributeFilterProvider : ActionDescriptorFilterProvider, System.Web.Http.Filters.IFilterProvider
{
    private readonly IUnityContainer _container;

    public UnityWebApiFilterAttributeFilterProvider(IUnityContainer container)
    {
        _container = container;
    }

    public IEnumerable<FilterInfo> GetFilters(HttpConfiguration configuration, HttpActionDescriptor actionDescriptor)
    {
        var filters = base.GetFilters(configuration, actionDescriptor);

        this.BuildUpAttributes(filters);

        return filters;
    }

    private void BuildUpAttributes(IEnumerable filterInfo)
    {
        foreach (FilterInfo filter in filterInfo)
        {
            object o = _container.BuildUp(filter.GetType(), filter);
        }
    }
}

我将此提供程序设置为 Global.asax 文件中的默认提供程序:

var providers = GlobalConfiguration.Configuration.Services.GetFilterProviders().ToList();
        //Remove the default provider
        var defaultprovider = providers.Single(i => i is ActionDescriptorFilterProvider);
        GlobalConfiguration.Configuration.Services.Remove(typeof(System.Web.Http.Filters.IFilterProvider), defaultprovider);
        //Add our custom provider
        GlobalConfiguration.Configuration.Services.Add(typeof(System.Web.Http.Filters.IFilterProvider), new UnityWebApiFilterAttributeFilterProvider(new UnityContainer()));

我还在 AuthorizationFilter 中添加了依赖项:

public class WebApplicationApiAuthorizeAttribute : System.Web.Http.AuthorizeAttribute
{

    [Dependency]
    public IAuthorizationHelper AuthorizationHelper { get; set; }

    #region OnAuthorization
    public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
{
    //Authorization code, which uses the AuthorizationHelper lives here
}   

}

我在 Unity 配置文件中设置了映射:

container.RegisterType<WebApplicationApiAuthorizeAttribute>(new InjectionMember[]
            {
                new InjectionProperty("AuthorizationHelper", new ResolvedParameter<IAuthorizationHelper>())
            });

        container.RegisterType<IAuthorizationHelper, WebAuthorizationHelper>(new InjectionMember[]
            {
                new InjectionProperty("Cache", new ResolvedParameter<ICache>(cacheType)),
                new InjectionProperty("UserSessionManager", new ResolvedParameter<IUserSessionManager>()),
                new InjectionProperty("AuthorizationPermissionManager", new ResolvedParameter<IAuthorizationPermissionManager>()),
                new InjectionProperty("ExceptionLogger", new ResolvedParameter<IExceptionLogger>()),
            });

我可以看到 UnityWebApiFilterAttributeFilterProvider 类中的“BuildUpAttributes”方法被执行,并且过滤器被传递到 _container.BuildUp(...) 方法中,但是,WebApplicationApiAuthorizeAttribute 中的“IAuthorizationHelper”依赖项没有得到解析。当我调试 WebApplicationApiAuthorizeAttribute 时,它​​为空。

那么为什么这种依赖性没有得到解决呢?


您的代码中有两个错误。

  1. 你正在建立FilterInfo对象而不是它的Instance http://msdn.microsoft.com/en-us/library/system.web.http.filters.filterinfo.instance%28v=vs.118%29.aspx:

    foreach (FilterInfo filter in filterInfo)
    {
        object o = _container.BuildUp(filter.GetType(), filter);
    }
    

    但这是正确的代码:

    foreach (FilterInfo filter in filterInfo)
    {
        _container.BuildUp(filter.Instance.GetType(), filter.Instance);
    }
    
  2. 您的定制UnityWebApiFilterAttributeFilterProvider得到一个新的空容器:

    GlobalConfiguration.Configuration.Services.Add(
        typeof(System.Web.Http.Filters.IFilterProvider), 
        new UnityWebApiFilterAttributeFilterProvider(new UnityContainer()));
    

    但您应该传递应用程序的配置容器:

    GlobalConfiguration.Configuration.Services.Add(
        typeof(System.Web.Http.Filters.IFilterProvider), 
        new UnityWebApiFilterAttributeFilterProvider(container));
    
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 ASP.New MVC 4 Web Api 进行授权过滤器依赖注入 的相关文章

随机推荐

  • Android - ViewRootImpl$CalledFromWrongThreadException

    我正在使用this http savagelook com blog android display images from the internet in android 显示来自互联网的图像 但它会抛出如下错误 04 12 13 45
  • Kafka Streams 在 HDFS 上查找数据

    我正在使用 Kafka Streams v0 10 0 1 编写一个应用程序 并希望通过查找数据来丰富我正在处理的记录 该数据 带时间戳的文件 每天 或每天 2 3 次 写入 HDFS 目录 我怎样才能将其加载到Kafka Streams应
  • FROM 子句中的 PostgreSQL json_array_elements - 为什么这不是笛卡尔连接?

    如果我有这样的表达 SELECT t json column gt gt x nested gt gt y FROM my table t json array elements t gt nested nested 为什么我不需要加入 更
  • 如何在mysql中启用INNODB

    当我在 MySQL 中执行查询时 它返回一个错误 指出 InnoDB 未启用 当我点击存储引擎时 InnoDB被禁用 如何启用 InnoDB 您需要在中启用它my cnf文件 然后重新启动服务器 http dev mysql com doc
  • 使用||在开关的情况下?

    因此 对于 Java 基础知识的大学实验室来说 我遇到了麻烦 我必须设置一个开关 并在该开关内放置一个盒子 有3个选项供用户输入 每个选项都可以用字母来回答 问题是这个字母允许是大写或小写 问题是我似乎不知道如何设置它 所以一个案例将允许其
  • Greasemonkey 脚本中的 XPath 未在 XHTML 页面上选择正确的节点

    我正在为 Greasemonkey 编写脚本微博网 我无法在 XHTML 页面上使用 XPath 选择元素 此代码无法获取我想要的元素 function resolver prefix return prefix x http www w3
  • iOS 11 - 键盘高度在键盘通知中返回 0

    我一直在使用键盘通知 没有任何问题 并且获得了键盘的准确高度 void keyboardDidShow NSNotification notification CGSize keyboardSize notification userInf
  • 删除 data.table 的分组变量

    我想用data table进行一些争论并希望我的结果数据表not包括分组变量 这是一个 MWE library data table DT lt data table x 1 10 grp rep 1 2 5 DT mmm mean x b
  • 使用 Robolectric 运行 Android 测试 - 依赖错误

    我使用的是 Android Studio 1 2 和 Windows 7 当按照此运行机器人电测试时example https github com nenick AndroidStudioAndRobolectric blob maste
  • 如何从 Objective-C 代码将文件保存到 $(PROJECT_DIR)?

    我有生成资源的代码 我想将其保存在 PROJECT DIR 的子目录中 如何在代码中从该环境变量获取真实路径 打开项目构建设置并添加SAVEPATH PROJECT DIR 到预处理器宏 然后你可以像这样获取项目目录 NSString pr
  • Android Studio中TextView和Button卡在蓝图的左上角

    当我在 Android Studio 中将 TextView 和 Button 添加到蓝图时 它会卡在蓝图的左上角 我遇到了同样的问题 单击 自动连接到父级 按钮 图标看起来像字母 U 磁铁符号 它位于设计视图的左上角
  • 执行查询并返回结果的方法

    应用程序无法运行 尝试执行查询来打印特定值 Method public Cursor trying String vg String q SELECT quantity FROM TABLE CONTACTS WHERE name vg S
  • 匈牙利算法的最少行数

    我想知道匈牙利算法覆盖所有零的最少行数 我已经关注了这个链接 但是那里的代码是一个贪婪的代码 匈牙利算法 如何用最少的行数覆盖0个元素 https stackoverflow com questions 14795111 hungarian
  • 什么是更好的? Password_hash 与 SHA256 与 SHA1 与 md5

    搭配什么比较好salt用于密码存储 MD5 hash md5 password salt 密码 哈希 hash password hash password PASSWORD DEFAULT salt SHA1 result sha1 sa
  • Oracle SQL 案例中的数字无效

    您好 我在处理 SQL 案例时遇到了麻烦 问题是我尝试运行具有 7 个不同列的案例 这些列可以具有不同类型的数据 字符串 日期 数字 具体取决于 id 这意味着在某些 id 下 列中的行将是字符串 而在其他 id 下 列中的行将是数字 我意
  • 纯ASP上传带图片检测

    如何将文件从浏览器上传到运行经典 ASP 的服务器并检测服务器端文件是否是有效图片 对于有效的图片 如何获取其尺寸 通常经典ASP中的文件上传是由第三方组件完成的 这些组件带有DLL文件 需要在服务器上注册 有时还需要花钱 不用说 出于安全
  • Spring Boot加载图片后上传

    我能够将图像上传到服务器 并且可以在路径中找到我的图像 static images gallery 现在 当我尝试加载上传的图像时 应用程序不显示主题 仅在应用程序重新启动后 我遇到了同样的问题 因为启动时加载了静态目录 上传路径一定要放在
  • 当mysql WHERE子句为空时,返回所有行

    randomvariable GET randomvariable search SELECT from objects WHERE transactiontype randomvariable order by id DESC Now i
  • 在asp.net mvc中动态添加文本框并将值保存到数据库

    我想通过单击添加按钮动态添加文本框 可以删除文本框 最后可以保存文本框中的列表值 我的模特班 public class CustModel public List
  • 使用 ASP.New MVC 4 Web Api 进行授权过滤器依赖注入

    我正在尝试在 MVC 4 Web Api 授权过滤器上实现依赖项注入 我创建了一个继承自 ActionDescriptorFilterProvider 的 FilterProvider public class UnityWebApiFil