在asp.net核心web api中间件中,是否可以访问中间件内的配置?有人可以指导我如何做到这一点吗?
答案 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。