ASP.NET - 301重定向

16

我该如何在ASP.NET中进行永久重定向? 我想将一个页面永久重定向到另一个页面,使用301重定向。

3个回答

37
protected void Page_PreInit(object sender, EventArgs e)
{
    Response.StatusCode = 301;
    Response.StatusDescription = "Moved Permanently";
    Response.RedirectLocation = "AnotherPage.aspx";
    HttpContext.Current.ApplicationInstance.CompleteRequest();
}

在4.0版本中,有一个简单的HttpResponse.RedirectPermanent()方法为你做了上述所有工作:

Response.RedirectPermanent("AnotherPage.aspx");

4
在我的辅助类中,我创建了一个扩展方法,使我可以输入Response.PermanentRedirect("someUrl.aspx"); - 方法调用为:public static void PermanentRedirect(this System.Web.HttpResponse response, string uri)。 - Zhaph - Ben Duguid
4
可以设置 Response.RedirectLocation,而无需调用 Response.AddHeader。 - orip

15
ASP.NET 4.0 Beta 1提供了一个Response.RedirectPermanent()方法,用于进行301重定向。
Response.RedirectPermanent("AnotherPage.aspx");

来自ASP.NET 4.0和Visual Studio 2010 Web Development Beta 1概述白皮书:

在Web应用程序中,常见做法是随着时间的推移移动页面和其他内容,这可能会导致搜索引擎中积累过时的链接。在ASP.NET中,开发人员通常使用Response.Redirect方法处理对旧URL的请求,将请求转发到新URL。然而,Redirect方法发出HTTP 302 Found(临时重定向)响应,当用户尝试访问旧URL时会导致额外的HTTP往返。

ASP.NET 4.0添加了一个新的RedirectPermanent帮助器方法,使得轻松发出HTTP 301 Moved Permanently响应成为可能。


3
如果您希望始终从一个URL重定向到另一个URL,您可以使用IIS Rewrite Module
在您的web.config文件中添加以下内容:
<system.webServer>
  <rule name="Redirect Source to Destination" stopProcessing="true">
    <match url="/source.aspx" />
    <action type="Redirect" url="/destination.aspx" redirectType="Permanent" />
  </rule>
</system.webServer>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接