Asp.net core 2.0 middleware - accessing config settings

﹥>﹥吖頭↗ 提交于 2019-12-05 11:51:42

In a middle-ware you can access settings. To achieve this, you need to get IOptions<AppSettings> in the middle-ware constructor. See following sample.

public static class HelloWorldMiddlewareExtensions
{
    public static IApplicationBuilder UseHelloWorld(
        this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<HelloWorldMiddleware>();
    }
}

public class HelloWorldMiddleware
{
    private readonly RequestDelegate _next;
    private readonly AppSettings _settings;

    public HelloWorldMiddleware(
        RequestDelegate next,
        IOptions<AppSettings> options)
    {
        _next = next;
        _settings = options.Value;
    }

    public async Task Invoke(HttpContext context)
    {
        await context.Response.WriteAsync($"PropA: {_settings.PropA}");
    }
}

public class AppSettings
{
    public string PropA { get; set; }
}

For more information see here.

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