Asp.Net MVC3重定向

时间:2011-05-05 14:09:45

标签: asp.net-mvc


我有一个如下所示的动作。在GetAvailableBookList中,我获取列表,如果没有任何可用的书重定向到消息页面。但在行动中,部分代码继续执行并获得异常,我发现自己处于错误页面。 我不想使用返回RedirectToAction或类似之类的东西,因为在我们的应用程序中有很多地方使用这个重定向逻辑。

    public ActionResult ActionName()
    {
        List<BookType> bookList = GetAvailableBookList();
        // some code
        return View("RelatedView");
    }

    private List<BookType> GetAvailableBookList()
    {
        ....
        list  = GetList();
        if(list.Count == 0)
        {
            System.Web.HttpContext.Current.Response.Redirect(messagePageUrl, true);
        }
        else return list;
    }

5 个答案:

答案 0 :(得分:1)

不幸的是,Response.Redirect()对ASP.NET MVC并不友好。我的经验法则是,如果它来自HttpContext,我不想在控制器中触摸它(当然,该规则有很多例外) - 特别是因为它提高了可测试性。

我的建议 使用RedirectToAction,但由于您不想重复代码,您可以这样做,以便您不必重复代码(尽管在这种情况下,我没有看到重复代码的问题。)

public ActionResult LoadBookListAndContinue(
  Func<List<BookType>, ActionResult> continuation)
{
   var list = LoadBooklist();
   if(list.Any())
   {
     return action(continuation); 
   }
   return new RedirectResult(messagePageUrl);
}


// in your controller
public ActionResult ActionName()
{
  return LoadBookListAndContinue(
    list => {
      // some code
      return View("RelatedView");
    });
}

漂亮吗?不,但它比Redirect例外更好。

答案 1 :(得分:0)

使用

return RedirectToAction("NoListAvailable");

如果您要执行特定操作。 NoListAvailable操作可以返回指示问题的视图。

或者,您可以直接返回视图

return View("NoListAvailable");

答案 2 :(得分:0)

您获得的异常可能是ThreadAbortException,除非您允许线程继续(Response.Redirect中的第二个参数),否则这是您无法避免的。

另一方面,您当前的解决方案通常存在缺陷。当方法返回空列表时,应在每个操作中使用RedirectToAction。

答案 3 :(得分:0)

抛出特定异常并重定向捕获它的位置可能是解决方案

答案 4 :(得分:0)

尝试写

System.Web.HttpContext.Current.Response.Redirect(messagePageUrl, false);