我有一些代码对于我的一些控制器操作很常见,这些操作被提取到一个私有的“帮助器”方法中,只是为了合并。该方法有望为我“获取”一个对象,尽管它会执行一些健全性/安全性检查,并且可能会将用户重定向到其他操作。
private Thingy GetThingy(int id)
{
var thingy = some_call_to_service_layer(id);
if( null == thingy )
Response.Redirect( anotherActionUrl );
// ... many more checks, all more complex than a null check
return thingy;
}
public ActionResult ActionOne(int id)
{
var thingy = GetThingy(id);
// do more stuff
return View();
}
// ... n more actions
public ActionResult ActionM(int id)
{
var thingy = GetThingy(id);
// do more stuff
return View();
}
这可以正常运行,但 Elmah 然后通知我异常:
System.Web.HttpException: Cannot redirect after HTTP headers have been sent.
所以,我的问题是:有没有更正确的方法来做我想做的事情?本质上,我想要的只是使当前操作停止处理,而是返回一个 RedirectToRouteResult。