[英]How do i get values from appsettings.json to BusinessLayer(my helper class) MVC 6
我的控制器通過調用API實習生返回用戶詳細信息
public class HomeController : Controller
{
public ActionResult AccountDetails(int userId)
{
return this.Content(new WebHelperService().GetAccountDetails(userId)), "application/json");
}
}
這是我在業務層中的 WebHelperService,我需要從appsettings.json獲取價值
public class WebHelperService { private string url = null; public WebHelperService() { //url = ConfigurationManager.ConnectionString["ExternalApiUrl"].ToString(); // ConfigurationManager is not available in .net core. //So How do i read ExternalApiUrl from appsettings.josn,Which is the best way } public string GetAccountDetails(int userId) { return WebCall("{'userId':" + userId + "}"); } private string WebCall(string data) { WebRequest request = WebRequest.Create(url); // get the data from url and returns it } }
讓我們暫時忘記您的特定用例,而只討論一般的.net core中的設置。 重要的是,我認為您正在嘗試從您的班級訪問原始AppSettings,但是您實際上要執行的操作是將其DI到班級中。 因此,讓我們這樣做。
考慮您有一個類似於以下內容的appSettings.json:
{
"myConfiguration": {
"myProperty": true
}
}
現在,您需要創建一個POCO來保存這些設置。 像這樣:
public class MyConfiguration
{
public bool MyProperty { get; set; }
}
在startup.cs中,應該有一個名為“ ConfigureServices”的方法。 在這里,您將像這樣調用一個“配置”您的設置。
public void ConfigureServices(IServiceCollection services)
{
services.Configure<MyConfiguration>(Configuration.GetSection("myConfiguration"));
}
因此,現在您想將該設置對象注入到一個類中。 現在將其稱為MyClass。 它看起來像以下內容:
public class MyClass : IMyClass
{
private readonly MyConfiguration _myConfiguration;
public MyClass(IOptions<MyConfiguration> myConfiguration)
{
_myConfiguration = myConfiguration.Value;
}
}
現在您可以訪問您的配置了!
獎金!
相反,您可以使您的ConfigureServices方法如下所示:
public void ConfigureServices(IServiceCollection services)
{
//services.Configure<MyConfiguration>(Configuration.GetSection("myConfiguration"));
services.AddSingleton(Configuration.GetSection("myConfiguration").Get<MyConfiguration>());
}
現在要做的是將您的服務綁定到實際的類上,而不是IOptions對象上。
現在,當您將其注入到類中時,您將注入POCO設置類,而不是IOptions。 像這樣:
public class MyClass : IMyClass
{
private readonly MyConfiguration _myConfiguration;
public MyClass(MyConfiguration myConfiguration)
{
_myConfiguration = myConfiguration;
}
}
進一步閱讀:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.