ASP.NET Core 2.0 URL Rewriting

Problem

How to implement URL rewriting in ASP.NET Core.

Solution

In Startup, configure RewriteOptions and middleware for URL rewriting.

Run and browse to /films. You’ll notice a redirect.

ASP.NET Core

Browse to /actors, you’ll notice a rewrite,

ASP.NET Core

Discussion

URL Rewriting is about modifying the request URL based on custom rules in order to decouple the address from the underlying resource. This could be for reasons like security, SEO, user-friendly URL, and redirect HTTP to HTTPS etc.

When you’re unable to use the rewriting features of web servers (IIS, Apache, Nginx), ASP.NET Core provides an alternate option, i.e., Response Rewrite middleware. Its performance and feature set won’t match the server based rewriting features though.

Rewrite middleware is capable of doing both redirects and rewrites.

Redirect

It’s a client-side operation and works like this,

  1. The client requests a resource e.g. /films.
  2. The server responds with status code 301 (Moved Permanently) or 302 (Found) with new Location header, instructing a client to request the new location e.g. /movies.
  3. Client makes a request to the new location which will also be shown in the address bar.

Rewrite

It’s a server-side operation and works like this,

  1. Client requests a resource e.g. /actors
  2. Server will internally map to new location e.g. /stars and return 200 (OK).
  3. Client will not know anything about this internal process and will still see the requested URL in address bar.

    Rules

    Redirect and Rewrite rules are Regular Expressions, details of which could be found in the "Useful Links" section below.

    Custom Rules

    You could also create custom rules by creating a class and implementing IRule interface.

    Custom rule can be added to RewriteOptions.

    Source Code

    GitHub

    Useful Links

    URL Rewriting