【问题标题】:How do you do a 301 permanant redirect route in ASP.Net MVC如何在 ASP.Net MVC 中执行 301 永久重定向路由
【发布时间】:2011-01-14 02:02:27
【问题描述】:

如何在 ASP.NET MVC 中做一个 HTTP 301 永久重定向路由?

【问题讨论】:

  • 302 是临时重定向 ... 301 是永久重定向

标签: asp.net asp.net-mvc redirect http-status-code-301 routes


【解决方案1】:

创建一个继承自 ActionResult 的类...

public class PermanentRedirectResult : ActionResult { public string Url { get; set; } public PermanentRedirectResult(string url) { this.Url = url; } public override void ExecuteResult(ControllerContext context) { context.HttpContext.Response.StatusCode = (int)HttpStatusCode.MovedPermanently; context.HttpContext.Response.RedirectLocation = this.Url; context.HttpContext.Response.End(); } }

那就用吧……

public ActionResult Action1() { return new PermanentRedirectResult("http://stackoverflow.com"); }

一个更完整的答案,将重定向到路由...Correct Controller code for a 301 Redirect

【讨论】:

【解决方案2】:

您想要一个 301 重定向,a 302 is temporary, a 301 is permanent。在本例中,context 是 HttpContext:

context.Response.Status = "301 Moved Permanently";
context.Response.StatusCode = 301;
context.Response.AppendHeader("Location", nawPathPathGoesHere);

【讨论】:

  • 第一行不需要,因为 StatusCode 也会设置适当的标签。状态已弃用。
猜你喜欢
  • 1970-01-01
  • 2012-02-24
  • 2014-01-12
  • 1970-01-01
  • 1970-01-01
  • 2021-02-03
  • 2011-06-07
  • 2014-09-24
  • 2013-07-17
相关资源
最近更新 更多