访问类库中的appsettings.json

时间:2017-10-17 07:06:47

标签: asp.net-core-mvc .net-core

我在类库中搜索访问appsettings.json的解决方案。我有一个ASP.NET Core Web应用程序,它依赖于类库。在这个类库中,我必须从appsettings.json中读取一些属性。

有没有办法做到这一点?

1 个答案:

答案 0 :(得分:3)

您应该使用选项

使用起来相当简单。看看这篇文章。它很好地解释了Src

1 /创建选项类

namespace UsingOptions.Models
{
    public class MyOptions
    {
        public MyOptions()
        {
            // Set default value.
            Option1 = "value1_from_ctor";
        }
        public string Option1 { get; set; }
        public int Option2 { get; set; } = 5;
    }
}

2 /在ConfigureServices方法中配置它(在startup.cs中)

public void ConfigureServices(IServiceCollection services)
{
    // Adds services required for using options.
    services.AddOptions();

    // Register the IConfiguration instance which MyOptions binds against.
    **services.Configure<MyOptions>(Configuration);**

    // Add framework services.
    services.AddMvc();
}

3 /将IOptions注入控制器

public class HomeController : Controller
{
    private readonly MyOptions _options;

    public HomeController(IOptions<MyOptions> optionsAccessor)
    {
        _options = optionsAccessor.Value;
    }

    public IActionResult Index()
    {
        var option1 = _options.Option1;
        var option2 = _options.Option2;
        return Content($"option1 = {option1}, option2 = {option2}");
    }
}