在ASP.NET MVC中,如何Response.Redirect的工作? [英] In ASP.NET MVC, how does response.redirect work?

查看:731
本文介绍了在ASP.NET MVC中,如何Response.Redirect的工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在经典的ASP和ASP.NET web表单中使用的Response.Redirect。然而,随着MVC 2.0,我遇到了一些奇特。

I have used response.redirect in classic ASP and ASP.NET webforms. However, with MVC 2.0, I am running into something peculiar.

我有一个由多个控制器的方法来帮助负载和验证的一些信息在控制器类中的私有方法。这家私人的方法是设置一个,如果发现问题到一个通用的错误信息页面重定向。

I have a private method in a controller class that is used by multiple controller methods to help load and validate some information. This private method is setup to redirect if a problem is discovered to a generic error message page.

我注意到的一个大问题是,呼叫控制器类和页面视图试图重定向实际发生之前完成渲染和加载。这是发展烦人,因为查看抛出我需要一般性的错误页面最后装入之前忽略的例外。

The big problem I am noticing is that the calling controller class and page view attempt to complete rendering and loading before the redirect actually takes place. This is annoying in development because the View throws exceptions that I need to ignore before my generic error page finally loads.

如前所述,我习惯的Response.Redirect的旧模式,prevented随后code页面上从作为新的页面,然后将加载执行。

As mentioned above, I am used to the older model of response.redirect which prevented subsequent code on a page from being executed as the new page would then load.

在MVC上重定向任何帮助或建议将不胜AP preciated。

Any help or advice on redirects in MVC would be greatly appreciated.

推荐答案

常规机制在ASP.Net MVC重定向是类型RedirectResult的对象返回给客户端。如果你叫查看方法之前做到这一点,你的观点方法将永远不会被调用。

The conventional mechanism to redirect in ASP.Net MVC is to return an object of type RedirectResult to the client. If this is done before your View method is called, your view methods will never be called.

如果你调用Response.Redirect的自己,而不是让Asp.Net MVC的前端控制器为你做的,你的控制器方法将继续,直到它完成或抛出异常。

If you call Response.Redirect yourself, instead of letting Asp.Net MVC's front controller do that for you, your controller method will continue on until it finishes or throws an exception.

有关问题的惯用解决方案是让你的私有方法返回一个结果,你的控制器可使用。

The idiomatic solution for your problem is to have your private method return a result that your controller can use.

例如:

public ActionResult Edit(MyEntity entity)
{
  if (!IsValid()) return Redirect("/oops/");
  ...
  return View();

}

private bool IsValid()
{
  if (nozzle==NozzleState.Closed) return false;
  if (!hoseAttached) return false;
  return (userRole==Role.Gardener);
}

这篇关于在ASP.NET MVC中,如何Response.Redirect的工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆