Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

asp.net-core

I've got a bothersome issue with ASP .NET vNext; more specifically, MVC.

Here is the 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 issue I am running into is very simple: The last middleware in the request pipeline does not always get called after app.UseMvc(). In fact, the only consistency I can make out of it is that I only see .SaveCookie() being called at the start of a new session (or a CTRL+F5).

Is there any rhyme or reason why my middleware isn't always being executed?

like image 940
Adam Sears Avatar asked Jan 07 '15 07:01

Adam Sears


1 Answers

If the request is handled by MVC, then it would send back the response to the client and not execute any middleware next in the pipeline.

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

Also since MVC could be writing the response, it would be too late for you to modify the response headers (as they are sent first to the client before the body). So you can use the OnSendingHeaders callback to get a chance to modify the headers.

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(...)
{
....
}
like image 141
Kiran Avatar answered Sep 28 '22 03:09

Kiran