且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ASP.NET Core 2.0中间件-访问配置设置

更新时间:2023-02-16 10:41:19

middle-ware中,您可以访问设置.为此,您需要在middle-ware构造函数中获取IOptions<AppSettings>.请参阅以下示例.

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.