ASP .NET vNext MVC 没有移交给管道中的下一个?

ASP .NET vNext MVC not handing off to next in pipeline?

我在使用 ASP .NET vNext 时遇到了一个麻烦的问题;更具体地说,MVC。

这是我的 Startup.cs 文件的简化版本:

public void ConfigureServices(IServiceCollection services)
{

    // Add MVC services to the services container.
    services.AddMvc();
    services.AddScoped<Foo>();

}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerfactory)
{

    app.Use(async (context, next) =>
    {
        await context.RequestServices.GetService<Foo>().Initialize(context);
        await next();
    });
    // Add MVC to the request pipeline.
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller}/{action}/{id?}",
            defaults: new { controller = "Home", action = "Index" });
    });

    // Time to save the cookie.
    app.Use((context, next) =>
    {
        context.RequestServices.GetService<Foo>().SaveCookie();
        return next();
    });
}

我遇到的问题非常简单:请求管道中的最后一个中间件并不总是在 app.UseMvc() 之后被调用。事实上,我能从中得出的唯一一致性是我只看到 .SaveCookie() 在新会话开始时被调用(或 CTRL+F5)。

为什么我的中间件不总是被执行有什么规律或原因吗?

如果请求由 MVC 处理,那么它会将响应发送回客户端,并且不会在管道中执行任何中间件 next

如果您需要在您的案例中做一些 post-processing 响应,那么您需要在 MVC 中间件之前注册它。

此外,由于 MVC 可能正在编写响应,因此您修改响应 headers 为时已晚(因为它们在 body 之前首先发送给客户端)。所以你可以使用 OnSendingHeaders 回调来获得修改 headers.

的机会

示例如下:

app.Use(async (context, next) =>
    {
        context.Response.OnSendingHeaders(
        callback: (state) =>
                  {
                      HttpResponse response = (HttpResponse)state;

                      response.Cookies.Append("Blah", "Blah-value");
                  }, 
        state: context.Response);

        await next(); // call next middleware ex: MVC
    });

app.UseMvc(...)
{
....
}