Simple app.map() not working MVC core

Viewed 1531

In Startup.cs i have a extremely simple Map

app.Map("/Home",x=>x.UseMiddlewareLogic1() );

My full code of Configure looks as shown below

public void Configure(IApplicationBuilder app)
        {
            app.Map("/Home",x=>x.UseMiddlewareLogic1() );
            //app.UseMiddlewareLogic1();
            //app.UseMiddlewareLogic2();
            app.Run(async context =>
             Logic3(context));
        }

Logic 3 is just a response write as shown below

 public async Task Logic3(HttpContext obj)
        {
            await obj.Response.WriteAsync("Logic 3\n");

        }

The above code shows 404 not found. The middleware logic class is the standard class which comes in the visual studio template. I am using VS 2017.

 public class MiddlewareLogic1
    {
        private readonly RequestDelegate _next;

        public MiddlewareLogic1(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext httpContext)
        {
            await httpContext.Response.WriteAsync("This is logic123 \n");
            await _next(httpContext);
        }
    }

    // Extension method used to add the middleware to the HTTP request pipeline.
    public static class MiddlewareLogic1Extensions
    {
        public static IApplicationBuilder UseMiddlewareLogic1(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<MiddlewareLogic1>();
        }

    }
1 Answers

This is your problem: app.Map("/Home",x=>x.UseMiddlewareLogic1() );.

If you are using app.Map, the framework will not execute middlewares outside Map branch (that are registered after app.Map - order of middleware is important). Instead, it will automatically terminate that. In other words, you never need use .Run inside .Map to terminate the pipeline.

And you get 404 as there is await _next(httpContext); in your MiddlewareLogic1 middleware used in Map, but there are no other pipelines registered in this Map branch. If you remove await _next(httpContext); you will see in response "This is logic123 instead of 404.


Update: both .Map and .MapThen have the same terminating behavior. As a solution, you may consider to - replace .Map to .Use and do query comparing login internally. - Or register a separate chain of middlewares in .app.Map.

Related