【问题标题】:How Middleware class receives parameters in Asp.NET Core中间件类在 Asp.NET Core 中如何接收参数
【发布时间】:2020-10-31 22:49:27
【问题描述】:

这是我的第一个问题,所以请不要严格判断
我试图了解 Middleware 如何从 Startup 类中的 Configure 方法接收参数。
中间件类的代码如下:

public class LocationMiddleware
{
    private RequestDelegate next;
    private MessageOptions options;

    public LocationMiddleware(RequestDelegate nextDelegate,IOptions<MessageOptions> opts)
    {
        next = nextDelegate;
        options = opts.Value;
    }

    public async Task Invoke(HttpContext context)
    {
        if (context.Request.Path=="/location")
        {
            await context.Response.WriteAsync($"{options.CityName}, {options.CountryName}");
        }
        else
        {
            await next(context);
        }
    }
}

这个类的构造函数有两个参数RequestDelegateIOptions&lt;MessageOptions&gt; 但是当在Startup 类中调用方法UseMiddleware 时,在这一行app.UseMiddleware&lt;LocationMiddleware&gt;(); 中没有发送任何参数@

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        app.UseMiddleware<LocationMiddleware>();

        app.UseRouting();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapGet("/", async context =>
            {
                await context.Response.WriteAsync("Hello World!");
            });
        });
    }

所以我的问题是中间件类如何接收这个参数?

【问题讨论】:

    标签: asp.net-core-3.1 asp.net-core-middleware


    【解决方案1】:

    这个类的构造函数有两个参数RequestDelegateIOptions&lt;MessageOptions&gt;但是当在Startup类中调用一个方法UseMiddleware时没有参数被发送到这一行app.UseMiddleware&lt;LocationMiddleware&gt;();

    我假设您在服务容器中添加/注册了MessageOptions,这将在您的自定义中间件中解析。

    services.Configure<MessageOptions>(Configuration.GetSection("MessageOptions"));
    

    此外,您可以查看the source code of UseMiddleware 以了解其工作原理。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-20
      • 2017-08-04
      • 1970-01-01
      • 1970-01-01
      • 2021-06-10
      • 2017-04-27
      • 1970-01-01
      相关资源
      最近更新 更多