Search code examples
.netasp.net-coreurl-rewritingroutesstartup

Why one needs to call UseRewriter() before defining routes in UseMvc()?


I created simple rewriter and called app.UseRewriter after defining routes:

app.UseMvc(routes =>
            {...});
app.UserRewriter(new RequestCatcher());

When I use browser and go to:

  • http:\\localhost:5050\test ApplyRule method is never executed

  • http:\\localhost:5050\test only requests for files like css,json,js are caught and processed in the ApplyRule method

     public class RequestCatcher : IRule
     {
        public RequestCatcher()
        {
        }
        public void ApplyRule(RewriteContext context)
        {
            var request = context.HttpContext.Request;
    
            if (request.Path.Value.EndsWith("/", StringComparison.OrdinalIgnoreCase))
            {
            }
        }
    }
    

Only when I move app.UseRewriter(rewriteOptions); call before defining routes all requests are processed in ApplyRule method. Why is that?


Solution

  • Middlewares are executed in the order they are registered. If you put it after UseMvc then only if Mvc did handle it, it would be rewritten. But at that point, its already too late since the action has been handled.

    See the Middlewares documentation.

    The order that middleware components are added in the Startup.Configure method defines the order in which the middleware components are invoked on requests and the reverse order for the response. The order is critical for security, performance, and functionality.