开发者

Asp.Net MVC3 Redirect

开发者 https://www.devze.com 2023-03-03 18:10 出处:网络
I have an action like shown below. In GetAvailableBookList, I get the list a开发者_开发问答nd if there is not any available book redirect to a message page. But in action part code continues to execu

I have an action like shown below. In GetAvailableBookList, I get the list a开发者_开发问答nd if there is not any available book redirect to a message page. But in action part code continues to execute and gets an exception and I find myself in error page. I don't want to use return RedirectToAction or something like that because there are a lot of places where we use this redirect logic in our application.

    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;
    }


Unfortunately, Response.Redirect() isn't really friendly with ASP.NET MVC. My rule of thumb is if it comes from HttpContext I don't want to touch it in the controller (of course there are many exceptions to that rule) -- especially since it improves testability.

My suggestion is to use RedirectToAction, but since you don't want to repeat code you can do it in such a way that you don't have to repeat code (although in this case I don't see a problem with repeating code).

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");
    });
}

Is it pretty? No, but it works better than the Redirect exception.


Use

return RedirectToAction("NoListAvailable");

if you have a specific action you would like to execute. The NoListAvailable action can return a view indicating the problem.

Alternatively, you could return the view directly

return View("NoListAvailable");


The exception you are getting is probably ThreadAbortException and this is something you cannot avoid unless you allow the thread to continue (2nd argument in Response.Redirect).

On a side note your current solution is generally flawed. You should use RedirectToAction in each action when your method returns an empty list.


Throwing a specific exception and redirect where you catch it may be solution


Try to write

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

精彩评论

暂无评论...
验证码 换一张
取 消