asp.net-mvc ASP.NET MVC 4 - RouteConfig.cs 中的 301 重定向

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16979234/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 02:55:06  来源:igfitidea点击:

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

asp.net-mvcasp.net-mvc-4asp.net-mvc-routing

提问by niico

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?

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

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?

我希望某些不同的路由指向同一个控制器操作 - 似乎 301 是最好的做法,特别是对于 SEO?

Thanks.

谢谢。

回答by Bastianon Massimo

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

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

public class RedirectController : Controller
{

    public ActionResult News()
    {

        // your code

        return RedirectPermanent("/News");
    }
}

in the global asax:

在全球 asax 中:

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

回答by Jonas Stawski

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+.

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