ASP.NET vNext MVC not sending to next in pipeline?

I have a bothersome problem with ASP.NET vNext; more specifically, MVC.

Here is a simplified version of my Startup.cs file:

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(); }); } 

The problem I am facing is very simple: the latest middleware in the request pipeline is not always called after app.UseMvc (). In fact, the only consistency I can make of this is that I only see .SaveCookie () is called at the start of a new session (or CTRL + F5).

Is there any rhyme or reason why my middleware is not always running?

+5
source share
1 answer

If the request is processed by MVC, it sends a response to the client and does not execute any middleware that follows the pipeline.

If you need to do some post-processing of the response in your case, you need to register it before the MVC middleware.

Also, since MVC can write a response, it would be too late to change the response headers (since they are first sent to the client in front of the body). This way you can use the OnSendingHeaders to be able to change the headers.

The following is an example:

 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(...) { .... } 
+4
source

Source: https://habr.com/ru/post/1210527/


All Articles