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

后端 未结 2 1072
孤独总比滥情好
孤独总比滥情好 2020-12-08 05:06

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

相关标签:
2条回答
  • 2020-12-08 05:33

    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>
    
    0 讨论(0)
  • 2020-12-08 05:34

    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" }
        );
    
    0 讨论(0)
提交回复
热议问题