ASP .NET vNext MVC没有传递到下一个管道?

Ada*_*ars 5 asp.net-core

我对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();
    });
}
Run Code Online (Sandbox Code Playgroud)

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

有没有押韵或理由为什么我的中间件并不总是被执行?

Kir*_*lla 5

如果请求被MVC处理,那么它会发送回客户端的响应,而不是执行任何中间件旁边的管道。

如果您需要在您的案例中对响应进行一些后处理,那么您需要在 MVC 中间件之前注册它。

此外,由于 MVC 可能正在编写响应,因此修改响应标头(因为它们在正文之前首先发送到客户端)对您来说为时已晚。因此,您可以使用OnSendingHeaders回调来获得修改标题的机会。

下面是一个例子:

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(...)
{
....
}
Run Code Online (Sandbox Code Playgroud)

  • 作为 RC2 的更新,该方法现在称为 OnStarting()。 (2认同)