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"); 
    } 
} 
相關問題