Tes*_*lo. 3 custom-attributes appsettings asp.net-core-mvc asp.net-core-1.1
我有一个 .NET Core 1.1 应用程序,在 HomeController 中的操作上设置了自定义属性。鉴于我需要属性逻辑内的配置文件 (appsettings.json) 中的值,是否可以在属性级别访问配置?
appsettings.json
{
"Api": {
"Url": "http://localhost/api"
}
}
Run Code Online (Sandbox Code Playgroud)
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)
{
}
}
Run Code Online (Sandbox Code Playgroud)
家庭控制器.cs
public class HomeController: Controller
{
[HandleSomething]
public IActionResult Index()
{
return View();
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
我也在做同样的事情。我做了一些类似于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();
}
Run Code Online (Sandbox Code Playgroud)
我可以像这样从属性中调用它:
public class SomeAttribute : Attribute
{
public SomeAttribute()
{
AppSettingsConfig.Configuration.GetValue<bool>("SomeBooleanKey");
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3865 次 |
| 最近记录: |