【问题标题】:Custom ASP.NET MVC ActionResult is not executed未执行自定义 ASP.NET MVC ActionResult
【发布时间】:2010-07-19 10:46:11
【问题描述】:

我使用here 中的PermanentRedirectResult 在 ASP.NET MVC 1 中执行 301 重定向。自从升级到 2.0 后,不再发送 301 响应。而是发送仅包含类名的 200 响应。

设置断点表示永远不会调用PermanentRedirectResult 上的ExecuteResult 方法。显然框架只是在结果上调用 ToString() 而不是执行它。

还有其他人看过吗?这是 2.0 中的故意更改吗?如果是,我现在需要做什么才能使用自定义 ActionResult?

【问题讨论】:

  • 你的方法是什么样的? (包括所有属性,如果有的话)

标签: asp.net-mvc asp.net-mvc-2


【解决方案1】:

Steve Sanderson's Pro ASP.NET MVC 2 Framework 做了一些修改,我强烈建议您购买。没有比这更好的资源了。

public class HomeController : Controller
{
  public ActionResult Index()
  {
    return RedirectToAction("Other").MakePermanent();
  }

  public ActionResult Other()
  {
    return View();
  }
}

public static class RedirectExtensions
{
  public static PermRedirectToRouteResult MakePermanent(this RedirectToRouteResult redirect)
  {
    return new PermRedirectToRouteResult(redirect);
  }

  public class PermRedirectToRouteResult : ActionResult
  {
    public RedirectToRouteResult Redirect { get; private set; }
    public PermRedirectToRouteResult(RedirectToRouteResult redirect)
    {
      this.Redirect = redirect;
    }
    public override void ExecuteResult(ControllerContext context)
    {
      Redirect.ExecuteResult(context);
      context.HttpContext.Response.StatusCode = 301;
    }
  }
}

【讨论】:

  • 我的问题原来是项目引用而不是 ActionResult 的实际代码,但有一个接受和赞成,因为 MakePermanent 扩展方法是处理 301 的更好方法,并测试此代码在我的项目中让我意识到我现有的 PermanentRedirectResult 出了什么问题。
【解决方案2】:

事实证明,包含PermanentRedirectResult 类的项目仍然引用了 ASP.NET MVC 1.0 程序集,尽管该网站已更新为引用 2.0。框架测试 action 方法的返回值,看它是 ActionResult 还是其他应该像这样包装在 ContentResult 中的东西......

return ((actionReturnValue as ActionResult) ??
  new ContentResult {
    Content = Convert.ToString(actionReturnValue, CultureInfo.InvariantCulture)
  });

...而(actionReturnValue as ActionResult) 为空,因为我的PermanentRedirectResult 扩展了错误的ActionResult,即1.0 程序集中的那个,而不是2.0 程序集中的那个。

更新引用以使 PermanentRedirectResult 是 2.0 ActionResult 解决了该问题。

【讨论】:

  • 谢谢。有同样的问题!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-29
  • 1970-01-01
  • 1970-01-01
  • 2021-01-26
  • 2012-04-19
相关资源
最近更新 更多