Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC 4 - 301 Redirects in RouteConfig.cs

How can I add a route to the RouteConfig.cs file in an ASP.NET MVC 4 app to perform a permanent 301 redirect to another route?

I would like certain different routes to point at the same controller action - it seems a 301 would be best practice for this, specially for SEO?

Thanks.

like image 791
niico Avatar asked Jun 07 '13 08:06

niico


People also ask

What is RouteConfig Cs in ASP NET MVC?

In MVC, routing is a process of mapping the browser request to the controller action and return response back. Each MVC application has default routing for the default HomeController. We can set custom routing for newly created controller. The RouteConfig. cs file is used to set routing for the application.

Where do I put 301 redirects?

Permanently redirect old pages or entire folders of pages to new locations in your Webflow site using the 301 Redirects settings: Open Project settings > Hosting > 301 redirects‍ Add the old URL in the “Old Path” field (eg. /old-url) Add the new URL in the “Redirect to Page” field (/entirely/new-url/structure)


2 Answers

You have to use RedirectPermanent, here's an example:

public class RedirectController : Controller {      public ActionResult News()     {          // your code          return RedirectPermanent("/News");     } } 

in the global asax:

    routes.MapRoute(         name: "News old route",         url: "web/news/Default.aspx",         defaults: new { controller = "Redirect", action = "News" }     ); 
like image 100
Bastianon Massimo Avatar answered Oct 16 '22 11:10

Bastianon Massimo


I know you specifically asked how to do this on the RouteConfig, but you can also accomplish the same using IIS Rewrite Rules. The rules live on your web.config so you don't even need to use IIS to create the rules, you can simply add them to the web.config and will move with the app through all your environments (Dev, Staging, Prod, etc) and keep your RouteConfig clean. It does require the IIS Module to be installed on IIS 7, but I believe it comes pre installed on 7.5+.

Here's an example:

<?xml version="1.0" encoding="UTF-8"?>  <configuration>     <system.webServer>         <rewrite>             <rules>                 <rule name="Redirect t and c" stopProcessing="true">                     <match url="^terms_conditions$" />                     <action type="Redirect" url="/TermsAndConditions" />                 </rule>             </rules>         </rewrite>     </system.webServer> </configuration> 
like image 43
Jonas Stawski Avatar answered Oct 16 '22 11:10

Jonas Stawski