Take advantage of URL Rewriting Middleware in ASP.NET Core to implement URL redirection and URL rewriting. Credit: Thinkstock URL rewriting is the process of altering request URLs based on one or more pre-defined rules. You can take advantage of the URL Rewriting Middleware in ASP.NET Core to work with URL redirection as well as URL rewriting. This article presents a discussion of how we can implement URL rewriting in ASP.NET Core. To work with the code examples illustrated in this article, you should have Visual Studio 2019 installed in your system. If you don’t already have a copy, you can download Visual Studio 2019 here. Create an ASP.NET Core API project First off, let’s create an ASP.NET Core project in Visual Studio. Assuming Visual Studio 2019 is installed in your system, follow the steps outlined below to create a new ASP.NET Core project in Visual Studio. Launch the Visual Studio IDE. Click on “Create new project.” In the “Create new project” window, select “ASP.NET Core Web Application” from the list of templates displayed. Click Next. In the “Configure your new project” window, specify the name and location for the new project. Click Create. In the “Create New ASP.NET Core Web Application” window shown next, select .NET Core as the runtime and ASP.NET Core 2.2 (or later) from the drop-down list at the top. I’ll be using ASP.NET Core 3.0 here. Select “API” as the project template to create a new ASP.NET Core API application. Ensure that the check boxes “Enable Docker Support” and “Configure for HTTPS” are unchecked as we won’t be using those features here. Ensure that Authentication is set as “No Authentication” as we won’t be using authentication either. Click Create. You should now have a new ASP.NET Core API project in Visual Studio. We’ll use this project in the subsequent sections of this article. Install URL Rewriting Middleware via NuGet Now that you have created an ASP.NET Core application in Visual Studio, the next thing you should do is install the necessary NuGet package(s). To work with the URL rewriting middleware in ASP.NET Core, you should have the Microsoft.AspNetCore.Rewrite package installed in your project. You can install this package from NuGet Package Manager inside the Visual Studio 2019 IDE. Alternatively, you can run the following command to install this package via the .NET CLI. dotnet add package Microsoft.AspNetCore.Rewrite URL redirection and URL rewriting URL redirection and URL rewriting are not the same. In URL redirection the server sends back HTTP status code 301 or 302 to the client and asks the client to access the resource using another URL. The client would then update the URL as appropriate and access the resource using the new URL. Thus, URL redirection happens at the client side, i.e., it is a client-side operation and requires a round trip to the server. By contrast, URL rewriting is a server-side operation. It is the process of modifying the request URL based on one or more pre-defined rules. In URL rewriting, the rewritten URL is not sent back to the client; the client is never aware that the resource resides in a different location than the one the client requested. Note that URL rewriting is nothing new—it has been around since the days of legacy ASP.NET. In URL rewriting, the rewriting of the URL happens at the server side and no round trips are necessary. Configure URL redirection in ASP.NET Core You can configure URL rewriting and URL redirection in the Startup class. In the Configure method of the Startup.cs file, add the following code to redirect HTTP requests to HTTPS. app.UseRewriter(new RewriteOptions() .AddRedirectToHttps()); Configure URL rewriting in ASP.NET Core The following code snippet is an example of URL rewriting. Note how the request URL is modified using the AddRewrite method. var rewrite = new RewriteOptions() .AddRewrite("api/values", "api/default", true); app.UseRewriter(rewrite); When you execute the application, you’ll observe that the HttpGet method of the DefaultController is called but the web browser shows this URL: http://localhost:52137/api/values You can also specify the rules using regex expressions as shown in the code snippet given below. var rewrite = new RewriteOptions() .AddRewrite(@"^Home/User?Code=(d+)", "Home/$1", true); app.UseRewriter(rewrite); Create a custom URL rewriting rule in ASP.NET Core To work with complex rules, you can create a custom rule as well. To do this, you need to create a class that extends the IRule interface and implements the ApplyRule method as shown in the code snippet given below. public class CustomRule : Microsoft.AspNetCore.Rewrite.IRule { public void ApplyRule(RewriteContext context) { throw new NotImplementedException(); } } The following code snippet illustrates how the ApplyRule method can be used. Note that the ApplyRule method shown here is for illustrative purposes only. You can change it as per your own requirements. public class CustomRule : Microsoft.AspNetCore.Rewrite.IRule { public void ApplyRule(RewriteContext context) { var request = context.HttpContext.Request; var host = request.Host; if (host.Host.Contains("localhost", StringComparison.OrdinalIgnoreCase)) { if(host.Port == 80) { context.Result = RuleResult.ContinueRules; return; } } var response = context.HttpContext.Response; response.StatusCode = (int)HttpStatusCode. BadRequest; context.Result = RuleResult.EndResponse; } } Add a custom rule to the rules collection in ASP.NET Core You can add your custom rule to the rules collection in the Configure method as shown in the code snippet given below. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { var options = new RewriteOptions(); options.Rules.Add(new CustomRule()) app.UseRewriter(options); } URL rewriting decouples the address from the underlying resource. You can take advantage of URL rewriting to provide user-friendly URLs that are simpler and easier to remember, as well as more meaningful to search engines. Related content how-to How to use FastEndpoints in ASP.NET Core Take advantage of the free open-source FastEndpoints library to build fast and lean APIs in your ASP.NET Core applications. By Joydip Kanjilal Jul 11, 2024 7 mins Microsoft .NET C# Development Libraries and Frameworks how-to How to use Refit to consume APIs in ASP.NET Core Take advantage of Refit REST library to simplify API consumption and make your code cleaner, more efficient, and easier to maintain. By Joydip Kanjilal Jul 04, 2024 10 mins C# Microsoft .NET Software Deployment how-to When to use an abstract class vs. interface in C# Understanding the differences between an abstract class and interface is key to designing loosely coupled and extensible applications. By Joydip Kanjilal Jun 20, 2024 10 mins Small and Medium Business Microsoft .NET C# how-to 6 security best practices for ASP.NET Core Learn the best practices and built-in safeguards for preventing attacks and protecting sensitive data in your ASP.NET Core web applications. By Joydip Kanjilal Jun 07, 2024 6 mins C# Microsoft .NET Web Development Resources Videos