【问题标题】:Asp.net core 2.0 middleware - Use parameters from appsettings which changes on runtimeAsp.net core 2.0 中间件 - 使用在运行时更改的 appsettings 中的参数
【发布时间】:2018-04-10 10:46:08
【问题描述】:

我们需要根据 appsettings.json 中的参数在中间件中做一些工作。有参数可以在运行时改变。

为此,我可以在设置文件注册时设置 reloadOnChange builder.AddJsonFile("appsettings.json", 可选:false,reloadOnChange:true)

这适用于我在控制器中使用 IOptionsSnapshopt 的情况,因为控制器是根据请求创建的。但是中间件是终生的。

我发现Asp.net core 2.0 middleware - accessing config settings 写了如何从 appsettings 访问参数。 --> 但如果参数在运行时发生变化,这将不起作用。

【问题讨论】:

    标签: c# asp.net-core-2.0 middleware


    【解决方案1】:

    根据文档ASP.NET Core Middleware: Per-request dependencies

    因为中间件是在应用启动时构建的,而不是按请求构建的,所以中间件构造函数使用的作用域生命周期服务不会在每个请求期间与其他依赖注入类型共享。如果您必须在中间件和其他类型之间共享范围服务,请将这些服务添加到 Invoke 方法的签名中。 Invoke 方法可以接受由依赖注入填充的附加参数。

    例如,将IOptionsSnapshot 参数添加到Invoke 方法中,而不是在构造函数中。

    public static class HelloWorldMiddlewareExtensions
    {
        public static IApplicationBuilder UseHelloWorld(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<HelloWorldMiddleware>();
        }
    }
    
    public class HelloWorldMiddleware
    {
        private readonly RequestDelegate _next;
    
        public HelloWorldMiddleware(RequestDelegate next)
        {
            _next = next;
        }
    
        public async Task Invoke(HttpContext context, IOptionsSnapshopt<AppSettings> options)
        {
            await context.Response.WriteAsync($"PropA: {options.Value.PropA}");
        }
    }
    
    public class AppSettings
    {
        public string PropA { get; set; }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-03-31
      • 1970-01-01
      • 1970-01-01
      • 2019-06-07
      • 2020-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多