DEV Community

Sardar Mudassar Ali Khan
Sardar Mudassar Ali Khan

Posted on

URL Rewrite in Asp.net Core MVC

In ASP.NET Core MVC, URL rewriting can be achieved using the URL Rewriting Middleware. The middleware allows you to modify or rewrite incoming request URLs before they are processed by the routing system. Here's how you can perform URL rewriting in ASP.NET Core MVC:

  1. Install the Microsoft.AspNetCore.Rewrite NuGet package to your project.

  2. Open the Startup.cs file in your ASP.NET Core MVC project.

  3. In the ConfigureServices method, add the following code to register the URL Rewriting Middleware:

using Microsoft.AspNetCore.Rewrite;

// ...

public void ConfigureServices(IServiceCollection services)
{
    // ...

    services.AddRouting();

    // ...
}
Enter fullscreen mode Exit fullscreen mode
  1. In the Configure method, add the following code to enable URL rewriting:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    // ...

    app.UseRouting();

    // Add the URL Rewriting Middleware
    app.UseRewriter(new RewriteOptions()
        .AddRedirect("old-url", "new-url") // Redirect a specific URL
        .AddRewrite("pattern", "replacement", skipRemainingRules: true) // Rewrite a specific URL pattern
    );

    // ...

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}"
        );
    });
}
Enter fullscreen mode Exit fullscreen mode
  1. In the AddRedirect method, specify the old-url and new-url parameters to redirect requests from the old URL to the new URL. You can also use the AddRewrite method to rewrite URLs based on a pattern and provide a replacement URL.

  2. You can add multiple AddRedirect and AddRewrite rules to handle different URL rewriting scenarios.

  3. Save the changes and run your ASP.NET Core MVC application. The specified URL rewriting rules will be applied to incoming requests.

Note: Make sure to define the URL rewriting middleware before the routing middleware (app.UseRouting()) to ensure that the rewritten URLs are processed correctly.

This is a basic example to get you started with URL rewriting in ASP.NET Core MVC. You can refer to the official Microsoft documentation for more advanced scenarios and options available with the URL Rewriting Middleware: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/url-rewriting

Top comments (0)