How to read appsettings.json in my _layout.chtml

十年热恋 提交于 2019-12-03 01:45:40

In .net core mvc you can inject the configuration by adding the following two lines at the top of your view:

@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration

You can then access the value like this:

@Configuration.GetSection("ApplicationInsights")["InstrumentationKey"]

Using ActionFilters you can interrupt the request and add the configuration variables maybe to the ViewBag so it becomes accessible from the views or from the _Layout.cshtml File.

For example, if the following configuration section is inside your appsettings.json

{
    "MyConfig": {
        "MyValue": "abc-def"
    }
}

In the code MyConfig.cs would be:

public class MyConfig
{
    public string MyValue{ get; set; }
}

First create a very simple ActionFilter which derives from IAsyncActionFilter as following :

public class SampleActionFilter : IAsyncActionFilter
{
    private MyConfig _options;
    public SampleActionFilter(IConfiguration configuration)
    {

        _options = new MyConfig();
        configuration.Bind(_options);
    }

    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        ((Microsoft.AspNetCore.Mvc.Controller)context.Controller).ViewBag.MyConfig = _options;
        await next();
    }
}

Later in the Startup.ConfigureServices method change services.AddMvc to the following:

public void ConfigureServices(IServiceCollection services)
{

    //..........

    services.AddMvc(options=>
    {
        options.Filters.Add(new SampleActionFilter(
            Configuration.GetSection("MyConfig")
        ));
    });

    //..........

}

To access the values just simply in the _Layout.cshtml or other view you can type:

@ViewBag.MyConfig.MyValue

If you use the options pattern you can inject them into your view like this:

@using Microsoft.Extensions.Options
@inject IOptions<ApplicationInsightsOptions> 
ApplicationInsightsOptionsAccessor
@
{
   var instrumentationKey = 
        ApplicationInsightsOptionsAccessor.Value.InstrumentationKey;
}

Options pattern in ASP.NET Core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!