Asp.net核心2.0中间件 - 访问配置设置

时间:2017-12-08 22:13:54

标签: asp.net-core-2.0 asp.net-core-webapi

在asp.net核心web api中间件中,是否可以访问中间件内的配置?有人可以指导我如何做到这一点吗?

1 个答案:

答案 0 :(得分:6)

middle-ware中,您可以访问设置。为此,您需要在IOptions<AppSettings>构造函数中获取middle-ware。见以下样本。

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; }
}

有关详细信息,请参阅here