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

时间:2017-08-29 08:32:06

标签: asp.net-core-mvc custom-attributes appsettings asp.net-core-1.1

我有一个.NET Core 1.1应用程序,在HomeController中的操作上设置了自定义属性。鉴于我需要在属性逻辑中使用配置文件(appsettings.json)中的值,是否可以在属性级别访问配置?

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();
     }
}

2 个答案:

答案 0 :(得分:3)

public HandleSomethingAttribute ()
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json");
    Configuration = builder.Build();

    string url = Configuration.GetSection("Api:Url").Value;
}

您好,请在属性构造函数中尝试此操作。它应该工作!

答案 1 :(得分:3)

我正在做同样的事情。我做了类似于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");
    }
}