如何读取.NET Core中属性内的配置(appsettings)值()

历览千载书,时时见遗烈。这篇文章主要讲述如何读取.NET Core中属性内的配置(appsettings)值?相关的知识,希望能为你提供帮助。
我有一个.NET Core 1.1应用程序,在HomeController中的动作上设置了自定义属性。鉴于我需要在属性逻辑中使用配置文件(appsettings.json)中的值,是否可以在属性级别访问配置?
【如何读取.NET Core中属性内的配置(appsettings)值()】appsettings.json

{ "Api": { "Url": "http://localhost/api" } }

HandleSomethingAttribute.cs
public class HandleSomethingAttribute : Attribute, IActionFilter { public void OnActionExecuting(ActionExecutingContext context) { // read the api url somehow from appsettings.json }public void OnActionExecuted(ActionExecutedContext context) { } }

HomeController.cs
public class HomeController: Controller { [HandleSomething] public IActionResult Index() { return View(); } }

答案
public HandleSomethingAttribute () { var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json"); Configuration = builder.Build(); string url = Configuration.GetSection("Api:Url").Value; }

嗨,在Attribute构造函数中尝试这个。它应该工作!
另一答案我也在做同样的事情。我做了类似于Dzhambazov的解决方案,但为了获得环境名称,我使用了Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")。我把它放在一个静态类中的静态变量中,我可以从项目的任何地方读取它。
public static class AppSettingsConfig { public static IConfiguration Configuration { get; } = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true) .Build(); }

我可以从属性中调用它,如下所示:
public class SomeAttribute : Attribute { public SomeAttribute() { AppSettingsConfig.Configuration.GetValue< bool> ("SomeBooleanKey"); } }


    推荐阅读