响应MVC中的永久重定向不发布301或更改URL

时间:2014-03-01 18:01:06

标签: asp.net-mvc redirect asp.net-mvc-5

我正在将旧的ASP.NET Web表单站点转换为ASP.NET MVC 5.我想为旧页面URL发出永久重定向。

这就是我所做的 -

RouteConfig.cs:

routes.MapRoute("About_old", 
      "About/About.aspx", 
      new { controller = "Home", action = "About_old" });

HomeController.cs:

public ActionResult About_old()
{
   return new RedirectResult("/About", true);

   // I've also tried 
   // return RedirectToActionPermanent("About"); 
   // return RedirectPermanent("/About");
}

所有尝试都会加载正确/关于视图,但URL不会更改,我在响应中看不到301代码。换句话说,URL是“localhost / About / About.aspx”,我希望它是“localhost / About”

Chrome的完整请求/响应:

Request URL:http://localhost:55774/About/About.aspx
Request Method:GET
Status Code:200 OK

Request Headers
GET /About/About.aspx HTTP/1.1
Host: localhost:55774
Connection: keep-alive
Cache-Control: max-age=0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.117 Safari/537.36
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8

Response Headers
Cache-Control:private
Content-Encoding:gzip
Content-Length:2284
Content-Type:text/html; charset=utf-8
Date:Sat, 01 Mar 2014 18:10:41 GMT
Server:Microsoft-IIS/8.0
Vary:Accept-Encoding
X-AspNet-Version:4.0.30319
X-AspNetMvc-Version:5.1
X-Powered-By:ASP.NET

我没有看到301,URL也没有变化。我必须认为这与我如何在RouteConfig.cs中映射旧aspx页面的路径有关,因为所有操作方法都具有相同的结果。 注意我已经在下面使用global.asax提供了一个解决方案,但是我希望它可以像我上面尝试的那样工作,所以我没有接受我的答案。

我做错了什么或者只是遗漏了什么?如何让301发布和更改URL?

1 个答案:

答案 0 :(得分:3)

这是我的解决方案(Global.asax)

protected void Application_PreRequestHandlerExecute(Object sender, EventArgs e)
        {
            string currentUrl = HttpContext.Current.Request.Path.ToLower();
            if (currentUrl.EndsWith("/about/about.aspx"))
            {
                Response.Status = "301 Moved Permanently";
                Response.AddHeader("Location", "/About");
                Response.End();
            }
        }

从这里回答:Global 301 redirection from domain to www.domain