如何在ASP.Net MVC中执行301永久重定向路由

时间:2010-02-07 13:28:01

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

如何在ASP.NET MVC中执行HTTP 301永久重定向路由?

2 个答案:

答案 0 :(得分:8)

创建一个继承自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

答案 1 :(得分: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);