更正301重定向的控制器代码

Jon*_*Jon 5 asp.net asp.net-mvc asp.net-mvc-routing

我正在从静态站点设计一个新的动态站点.我的路线全部排序但我对我的Action方法有疑问.

下面是代码,但是当测试并查看Firebug报告的标头时,如果我取出Response.End它是302重定向我假设因为我设置了301然后调用另一个动作使它成为302,但如果我放入Response.End我得到301.

我猜测添加Response.RedirectLocation实际上正在进行301重定向,所以我是否将我的返回值更改为EmptyResult或null,即使该行代码永远不会被执行,因此应用程序编译?

public ActionResult MoveOld(string id)
{
    string pagename = String.Empty;

    if(id == "2")
    {
      pagename = WebPage.SingleOrDefault(x => x.ID == 5).URL;
    }

    Response.StatusCode = 301;
    Response.StatusDescription = "301 Moved Permanently";
    Response.RedirectLocation = pagename;
    Response.End();

    return RedirectToAction("Details", new { pageName = pagename });
}
Run Code Online (Sandbox Code Playgroud)

Dan*_*son 14

我赞同列维的评论.这不是控制器的工作.我倾向于使用这个自定义ActionResult for 301's.以下是具有更多选项的修改版本.

对于ASP.NET MVC v2 +,请使用RedirectResult.

public class PermanentRedirectResult : ActionResult
{
  public string Url { get; set; }

  public PermanentRedirectResult(string url)
  {
    Url = url;
  }

  public PermanentRedirectResult(RequestContext context, string actionName, string controllerName)
  {
    UrlHelper urlHelper = new UrlHelper(context);
    string url = urlHelper.Action(actionName, controllerName);

    Url = url;
  }

  public PermanentRedirectResult(RequestContext context, string actionName, string controllerName, object values)
  {
    UrlHelper urlHelper = new UrlHelper(context);
    string url = urlHelper.Action(actionName, controllerName, values);

    Url = url;
  }

  public PermanentRedirectResult(RequestContext context, string actionName, string controllerName, RouteValueDictionary values)
  {
    UrlHelper urlHelper = new UrlHelper(context);
    string url = urlHelper.Action(actionName, controllerName, values);

    Url = url;
  }

  public override void ExecuteResult(ControllerContext context)
  {
    if (context == null)
    {
      throw new ArgumentNullException("context");
    }
    context.HttpContext.Response.StatusCode = 301;
    context.HttpContext.Response.RedirectLocation = Url;
    context.HttpContext.Response.End();
  }
}
Run Code Online (Sandbox Code Playgroud)

用法在动作中

//Just passing a url that is already known
return new PermanentRedirectResult(url);

//*or*

//Redirect to a different controller/action
return new PermanentRedirectResult(ControllerContext.RequestContext, "ActionName", "ControllerName");
Run Code Online (Sandbox Code Playgroud)