DEV Community

Sardar Mudassar Ali Khan
Sardar Mudassar Ali Khan

Posted on

URL Rewrite in Asp.net MVC

In ASP.NET MVC, URL rewriting can be achieved using the UrlRewrite module provided by IIS (Internet Information Services) or by implementing custom route handlers within the MVC framework. I'll provide an overview of both approaches.

  1. URL Rewriting with IIS UrlRewrite module: The IIS UrlRewrite module allows you to define rules for rewriting URLs at the server level. Here's how you can use it with ASP.NET MVC:

Step 1: Install the UrlRewrite module (if not already installed) on your server.
Step 2: Create a file named "web.config" in the root directory of your ASP.NET MVC application (if it doesn't exist).
Step 3: Add the following configuration inside the <system.webServer> section of the web.config file:

   <rewrite>
     <rules>
       <rule name="Rewrite to Controller/Action">
         <match url="^some-pattern$" /> <!-- Specify the pattern you want to rewrite -->
         <action type="Rewrite" url="ControllerName/ActionName" /> <!-- Specify the target controller and action -->
       </rule>
     </rules>
   </rewrite>
Enter fullscreen mode Exit fullscreen mode

Step 4: Save the web.config file, and IIS will now handle the URL rewriting based on the defined rules.

This approach allows you to define various rewrite rules using regular expressions to match specific patterns and redirect them to the desired controller and action.

  1. Custom Route Handlers in MVC: In ASP.NET MVC, you can also handle URL rewriting within the MVC framework by creating custom route handlers. This approach provides more flexibility and control over URL rewriting. Here's an example:

Step 1: Open the RouteConfig.cs file located in the App_Start folder of your MVC application.
Step 2: Inside the RegisterRoutes method, add a custom route that handles the rewriting:

   routes.Add(new Route("some-pattern", new MvcRouteHandler())
   {
       Defaults = new RouteValueDictionary(new { controller = "ControllerName", action = "ActionName" })
   });
Enter fullscreen mode Exit fullscreen mode

Step 3: Replace "some-pattern" with the actual URL pattern you want to rewrite.
Step 4: Replace "ControllerName" and "ActionName" with the target controller and action respectively.

With this approach, whenever a request matches the specified pattern, it will be internally routed to the specified controller and action, without changing the URL in the browser.

Both approaches have their own advantages and are suitable for different scenarios. Choose the one that best fits your requirements.

Top comments (0)