Rewrite rules in ASP.NET core middleware

Hans Arne Vartdal

If you, like me, came from the ASP.NET MVC world when you started with SPAs and Angular, you have probably at some point created a "one controller, one view MCV application", hosting the starting point of your Angular application. We could question how sensible that is, but either way, one issue you would run into doing this is conflicting routing between Angular and IIS.

To get HTML5-mode routing working, you need to hit the base url of your application to at all enable evaluation of the route, but IIS will first evaluate the route, and complain about no such resource existing.

Previously we have been able to fix this using rewrite rules in web.config, like this:

This worked both with ASP.NET and ASP.NET Core RC1, but when moving to RC2 this stopped working, for several reasons, but mainly that the web.config moved, and that the conditions didn't match correctly any more. You can read more about this in Issue 192 on IISIntegration.

As ASP.NET Core is cross platform MS wanted to move this concern into a new middleware to make it work regardless of IIS, and this new middleware has just been released! It is called Microsoft.AspNetCore.Rewrite, and you can look into the implementation under aspnet/BasicMiddleware on github.

You can now simply install the nuget, and add app.UseRewriter(...) in your startup.cs:

Voila, you no longer need the rewrite rule in web.config.

Be aware that the package requires you to upgrade Microsoft.AspNetCore.Http.Abstractions to version 1.1.0, but i have no compatibility issues with that.

NB: At the moment this is bleeding edge, as the nuget package version 1.0.0 is just 4 days old, released 16. November, and have just passed 100 downloads.

comments powered by Disqus