Asp.net 核心 2.0 中间件 - 访问配置设置
Asp.net core 2.0 middleware - accessing config settings
在asp.net核心网络api中间件中,是否可以访问中间件内部的配置?有人可以指导我如何完成吗?
在 middle-ware
中,您可以访问设置。为此,您需要在 middle-ware
构造函数中获取 IOptions<AppSettings>
。请参阅以下示例。
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。
在asp.net核心网络api中间件中,是否可以访问中间件内部的配置?有人可以指导我如何完成吗?
在 middle-ware
中,您可以访问设置。为此,您需要在 middle-ware
构造函数中获取 IOptions<AppSettings>
。请参阅以下示例。
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。