问:


ASP.NET CORE MVC 如何在Filter中使用依赖注入来读取AppSettings

答:


Dependency injection is possible in filters as well.

Here is a simple way to get connection string

public class EBisUserAuthResourceFilter : Attribute, IResourceFilter
{private readonly string connectionString;public EBisUserAuthResourceFilter(IConfiguration configuration){this.connectionString = configuration.GetSection("ConnectionStrings:DefaultConnection").Value;}public void OnResourceExecuted(ResourceExecutedContext context){// use this.connectionString
    }public void OnResourceExecuting(ResourceExecutingContext context){// use this.connectionString
    }
}

Now you can use this filter

[ServiceFilter(typeof(EBisUserAuthResourceFilter))]
public class HomeController : Controller
{  }

You also need to add this Filter to the service collection

public void ConfigureServices(IServiceCollection services)
{services.AddScoped<EBisUserAuthResourceFilter>();// your existing code to add other services
}

Another solution is to have a class representing the structure of the content of AppSettings.json file or a sub section and load that in your Startup classes' ConfigureServices method

services.Configure<SiteSettings>(Configuration);

and now you can inject IOptions<SiteSettings> in the constructor of your filter and use the needed property values. I prefer this as it is less magic strings in my code.

public class EBisUserAuthResourceFilter : Attribute, IResourceFilter
{private readonly string connectionString;public EBisUserAuthResourceFilter(IOptions<SiteSettings> settings){this.connectionString = settings.Value.connectionString ;}public void OnResourceExecuted(ResourceExecutedContext context){// use this.connectionString
    }public void OnResourceExecuting(ResourceExecutingContext context){// use this.connectionString
    }
}

原文链接

补充:


当然还有个更简单的办法,就是在Filter里面直接通过.Net Core App的方式来读取AppSettings的值,这个方法是最灵活的:

appsettings.json

{"Logging": {"IncludeScopes": false,"LogLevel": {"Default": "Warning"}},"AppSettings": {"CacheTimeSpan": 1200,"MD5PrivateKey": "KOPX&VDtt!890912hjk","Auth_UserName": "Username","Auth_Token": "Token"}
}

构造一个AppSettings类来反序列化appsettings.json文件中AppSettings节点下的内容:

public class AppSettings
{public int CacheTimeSpan { get; set; }public string MD5PrivateKey { get; set; }public string Auth_UserName { get; set; }public string Auth_Token { get; set; }
}

在Filter的构造函数中,构造AppSettings并读取其值:

public class AuthenticationFilterAttribute : Attribute, IAuthorizationFilter
{public AuthenticationFilterAttribute(){var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);IConfigurationRoot configuration = builder.Build();var appSettings=configuration.GetSection("AppSettings").Get<AppSettings>();int cacheTimeSpanValue = appSettings.CacheTimeSpan;}public void OnAuthorization(AuthorizationFilterContext context){}
}

ASP.NET CORE MVC 2.0 如何在Filter中使用依赖注入来读取AppSettings相关推荐

  1. ASP.NET Core MVC 6.0项目的文件夹结构

    介绍 在本文中,我将向您解释 ASP.NET Core MVC 6.0 Web 应用程序的默认文件夹结构,并描述每个文件夹的用途. 使用以下链接阅读我以前的文章. 如何创建 ASP.NET Core ...

  2. ASP.NET Core Web 应用程序系列(一)- 使用ASP.NET Core内置的IoC容器DI进行批量依赖注入(MVC当中应用)...

    在正式进入主题之前我们来看下几个概念: 一.依赖倒置 依赖倒置是编程五大原则之一,即: 1.上层模块不应该依赖于下层模块,它们共同依赖于一个抽象. 2.抽象不能依赖于具体,具体依赖于抽象. 其中上层就 ...

  3. asp.net core mvc权限控制:在视图中控制操作权限

    在asp.net core mvc中提供了权限验证框架,前面的文章中已经介绍了如何进行权限控制配置,权限配置好后,权限验证逻辑自动就会执行,但是在某些情况下,我们可能需要在代码里或者视图中通过手工方式 ...

  4. ASP.NET Core MVC 从入门到精通之初窥门径

    随着技术的发展,ASP.NET Core MVC也推出了好长时间,经过不断的版本更新迭代,已经越来越完善,本系列文章主要讲解ASP.NET Core MVC开发B/S系统过程中所涉及到的相关内容,适用 ...

  5. ASP.NET Core MVC从入门到精通[PDF版]

    随着技术的发展,ASP.NET Core MVC也推出了好长时间,经过不断的版本更新迭代,已经越来越完善,本系列文章主要讲解ASP.NET Core MVC开发B/S系统过程中所涉及到的相关内容,适用 ...

  6. ASP.NET Core MVC 从入门到精通之路由

    随着技术的发展,ASP.NET Core MVC也推出了好长时间,经过不断的版本更新迭代,已经越来越完善,本系列文章主要讲解ASP.NET Core MVC开发B/S系统过程中所涉及到的相关内容,适用 ...

  7. asp 判断数组等于_如何在 ASP.NET Core MVC 中处理 404 错误

    译文链接:https://www.infoworld.com/article/3545304/how-to-handle-404-errors-in-aspnet-core-mvc.html http ...

  8. ssm框架使用重定向报404_如何在 ASP.NET Core MVC 中处理 404 错误

    译文链接:https://www.infoworld.com/article/3545304/how-to-handle-404-errors-in-aspnet-core-mvc.html asp. ...

  9. 如何在 Asp.Net Core MVC 中处理 null 值

    译文链接:https://www.infoworld.com/article/3434624/how-to-handle-null-values-in-aspnet-core-mvc.html 传统的 ...

最新文章

  1. 枚举 ---- Codeforces Round #711 (Div. 2) D. Bananas in a Microwave[枚举暴力+思维优化]
  2. SparkSQL ThriftServer 安全相关功能的现状分析
  3. ab -压测模拟并发的工具
  4. mysql mydumper_mysql数据库备份之mydumper
  5. 【蓝桥杯Java_C组·从零开始卷】第七节、递归
  6. 本地如何搭建IPv6环境测试你的APP
  7. matlab电压稳定极限,电力系统电压稳定性的Matlab建模分析
  8. 我的世界服务器拔刀修复,我的世界拔刀剑怎么修复
  9. cocos2dx java调lua,【Tech-Lua】Cocos-2dx-Lua調用java的小白教程(二)
  10. 【论文】基于层次化注意力图网络和多视角学习的商品推荐(附论文下载链接)...
  11. 注水、占坑、瞎掰:起底机器学习学术圈的那些“伪科学”
  12. 综合案例—Spark实时交易数据统计
  13. 联想3650m4服务器硬盘指示灯,IBM x3650M4面板Board亮黄灯 故障维修
  14. 微信公众号开发笔记(二):微信分享接口实现和问题
  15. 在线加密解密网站大全2022(更新中ing)
  16. HDU 1983:Kaitou Kid - The Phantom Thief (2)
  17. 格林深瞳一面、二面、hr
  18. 2011 年互联网十大浏览器
  19. DE405/406星历表算法
  20. RK3399参考设计方案之DC-DC电源芯片RK808D【转】

热门文章

  1. Yoga710笔记本Win10和Ubuntu系统共存
  2. ANN:DNN结构演进History—LSTM网络
  3. 利用事件进行窗体间传值
  4. AJAX应用【股票案例、验证码校验】
  5. 如何在HTTP客户端与服务器端之间保持状态(转)
  6. Oracle 数据库Patch概念性小常识 PSU,CPU,bundle patch
  7. 源码编译LAMP平台
  8. MySQL学习笔记(6)之设计范式
  9. PHP两个字符串比较(人为出错),两字符串类型和数据表面相等,但strcmp()结果不为0...
  10. unix、linux 命令