ASP.NET MVC 4 - 301在RouteConfig.cs中重定向

时间:2013-06-07 08:11:19

标签: asp.net-mvc asp.net-mvc-4 asp.net-mvc-routing

如何在ASP.NET MVC 4应用程序中添加路由到RouteConfig.cs文件以执行永久301重定向到另一个路由?

我希望某些不同的路线指向相同的控制器动作 - 看起来301是最佳实践,特别是对于SEO?

感谢。

2 个答案:

答案 0 :(得分:49)

你必须使用RedirectPermanent,这是一个例子:

public class RedirectController : Controller
{

    public ActionResult News()
    {

        // your code

        return RedirectPermanent("/News");
    }
}

在全球的asax中:

    routes.MapRoute(
        name: "News old route",
        url: "web/news/Default.aspx",
        defaults: new { controller = "Redirect", action = "News" }
    );

答案 1 :(得分:25)

我知道您在RouteConfig上明确询问了如何执行此操作,但您也可以使用IIS Rewrite Rules完成相同操作。这些规则存在于您的web.config中,因此您甚至不需要使用IIS来创建规则,您只需将它们添加到web.config中,然后随应用程序一起移动到所有环境中(Dev,Staging,Prod,等)并保持您的RouteConfig干净。它确实需要在IIS 7上安装IIS模块,但我相信它预装在7.5 +上。

以下是一个例子:

<?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>
相关问题