1

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

你能分享你拥有什么,你要完成的一些代码? – Shoe

+0

@Shoe看到更新的问题 –

+2

同样的问题在这里...你能解决它吗? – Dzhambazov

回答

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

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

嗨,在属性构造函数中试试这个。它应该工作!

+0

我如何访问环境名称?因为我有针对开发和生产的不同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"); 
    } 
} 
相关问题