【问题标题】:How to read configuration (appsettings) values inside attribute in .NET Core?如何读取 .NET Core 中属性内的配置(appsettings)值?
【发布时间】:2018-02-06 15:01:12
【问题描述】:

我有一个 .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();
     }
}

【问题讨论】:

  • 你能分享一些你所拥有的和你想要完成的代码吗?
  • @Shoe 查看更新的问题
  • 同样的问题...你能解决它吗?
  • @Dzhambazov 还没有...

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


【解决方案1】:
public HandleSomethingAttribute ()
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json");
    Configuration = builder.Build();

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

你好,在 Attribute 构造函数中试试这个。它应该可以工作!

【讨论】:

  • 我如何访问环境名称?因为我有不同的 appSettings 用于开发和生产
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2017-02-09
    • 2015-10-05
    • 1970-01-01
    • 1970-01-01
    • 2018-02-18
    • 2018-07-22
    • 2017-02-17
    • 1970-01-01
    • 2017-04-04
    相关资源
    最近更新 更多