How do you do a HTTP 301 permanant redirect route in ASP.NET MVC?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Create a class that inherits from 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();
}
}
Then to use it...
public ActionResult Action1()
{
return new PermanentRedirectResult("http://stackoverflow.com");
}
A more complete answer that will redirect to routes... Correct Controller code for a 301 Redirect
回答2:
You want a 301 redirect, a 302 is temporary, a 301 is permanent. In this example,context
is the HttpContext:
context.Response.Status = "301 Moved Permanently";
context.Response.StatusCode = 301;
context.Response.AppendHeader("Location", nawPathPathGoesHere);