How to use URL Rewriting Middleware in ASP.NET Core
By FoxLearn 1/3/2025 8:35:26 AM 307
It supports both URL redirection (sending users to a different URL) and URL rewriting (changing the request URL before processing it).
To begin, let's create a new ASP.NET Core project in Visual Studio.
To use the URL rewriting middleware, you need to install the Microsoft.AspNetCore.Rewrite package. This can be done via the NuGet Package Manager in Visual Studio or by using the .NET CLI with the appropriate command.
dotnet add package Microsoft.AspNetCore.Rewrite
URL redirection and URL rewriting
URL redirection and URL rewriting are distinct processes.
URL redirection involves the server sending an HTTP status code (301 or 302) to the client, instructing it to access a resource using a different URL. This is a client-side operation and requires a round trip to the server, as the client updates the URL.
URL rewriting, on the other hand, is a server-side process where the request URL is modified based on predefined rules without informing the client. The client remains unaware of the change in the resource's location, and no round trips are necessary.
URL rewriting has been available since legacy ASP.NET and operates entirely on the server side.
Configure URL redirection in ASP.NET Core
You can configure URL rewriting and redirection in the Startup
class. In the Configure
method of the Startup.cs
file, you can add code to redirect HTTP requests to HTTPS.
app.UseRewriter(new RewriteOptions() .AddRedirectToHttps());
Configure URL rewriting in ASP.NET Core
The following code demonstrates how to rewrite URLs using the AddRewrite
method:
var rewrite = new RewriteOptions() .AddRewrite("products/list", "products/all", true); app.UseRewriter(rewrite);
In this case, when you navigate to the URL /products/list
, the request is internally rewritten to /products/all
, but the browser still displays the original URL.
Using Regular Expressions for URL Rewriting
You can also define more complex rewriting rules using regular expressions. Here's an example where we rewrite URLs that include a product ID:
var rewrite = new RewriteOptions() .AddRewrite(@"^products/(\d+)", "products/details/$1", true); app.UseRewriter(rewrite);
This rule rewrites any request like /products/123
to /products/details/123
.
Creating a Custom URL Rewriting Rule
If you need custom logic for URL rewriting, you can implement your own rule by creating a class that extends the IRule
interface and overriding the ApplyRule
method.
public class CustomRule : Microsoft.AspNetCore.Rewrite.IRule { public void ApplyRule(RewriteContext context) { throw new NotImplementedException(); } }
How to use the ApplyRule
method in C#?
public class CustomRedirectRule : Microsoft.AspNetCore.Rewrite.IRule { public void ApplyRule(RewriteContext context) { var request = context.HttpContext.Request; var path = request.Path.Value; // Redirect requests to the old "/old-path" to the new "/new-path" if (path.Contains("/old-path")) { context.HttpContext.Response.Redirect("/new-path", permanent: true); context.Result = RuleResult.EndResponse; } } }
In this example, if a request comes to /old-path
, it will be permanently redirected to /new-path
.
Adding a Custom Rule to the Rewriting Pipeline
To apply your custom rule, add it to the RewriteOptions
in the Configure
method of the Startup.cs
file:
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { var options = new RewriteOptions(); options.Rules.Add(new CustomRedirectRule()); app.UseRewriter(options); }
By using URL rewriting, you can create clean, user-friendly URLs that are easier to remember and more meaningful for search engines. This also allows you to map old URLs to new ones without affecting users or search engine rankings, providing better flexibility and maintaining SEO performance.
- Content Negotiation in Web API
- How to fix 'InvalidOperationException: Scheme already exists: Bearer'
- How to fix System.InvalidOperationException: Scheme already exists: Identity.Application
- Add Thread ID to the Log File using Serilog
- Handling Exceptions in .NET Core API with Middleware
- InProcess Hosting in ASP.NET Core
- Limits on ThreadPool.SetMinThreads and SetMaxThreads
- Controlling DateTime Format in JSON Output with JsonSerializerOptions