ASP.NET Core Response.End()?

Michael W Riemer Jr picture Michael W Riemer Jr · Oct 23, 2016 · Viewed 10.2k times · Source

I am trying to write a piece of middleware to keep certain client routes from being processed on the server. I looked at a lot of custom middleware classes that would short-circuit the response with

context.Response.End();

I do not see the End() method in intellisense. How can I terminate the response and stop executing the http pipeline? Thanks in advance!

public class IgnoreClientRoutes
{
    private readonly RequestDelegate _next;
    private List<string> _baseRoutes;

    //base routes correcpond to Index actions of MVC controllers
    public IgnoreClientRoutes(RequestDelegate next, List<string> baseRoutes) 
    {
        _next = next;
        _baseRoutes = baseRoutes;

    }//ctor


    public async Task Invoke(HttpContext context)
    {
        await Task.Run(() => {

            var path = context.Request.Path;

            foreach (var route in _baseRoutes)
            {
                Regex pattern = new Regex($"({route}).");
                if(pattern.IsMatch(path))
                {
                    //END RESPONSE HERE

                }

            }


        });

        await _next(context);

    }//Invoke()


}//class IgnoreClientRoutes

Answer

gretro picture gretro · Oct 23, 2016

End does not exist anymore, because the classic ASP.NET pipeline does not exist anymore. The middlewares ARE the pipeline. If you want to stop processing the request at that point, return without calling the next middleware. This will effectively stop the pipeline.

Well, not entirely, because the stack will be unwound and some middlewares could still write some data to the Response, but you get the idea. From your code, you seem to want to avoid further middlewares down the pipeline from executing.

EDIT: Here is how to do it in the code.

public class Startup
{
    public void Configure(IApplicationBuilder app)
    {
        app.Use(async (http, next) =>
        {
            if (http.Request.IsHttps)
            {
                // The request will continue if it is secure.
                await next();
            }

            // In the case of HTTP request (not secure), end the pipeline here.
        });

        // ...Define other middlewares here, like MVC.
    }
}