mvc中用response.redirect跳转后,后续代码还会执行的问题

来源:互联网 发布:java语句执行顺序 编辑:程序博客网 时间:2024/04/30 07:18

model.JobInfo = js.GetJob(id);
if (model.JobInfo == null)
{
Response.Redirect(“/”, true);
}
model.CompInfo = (new CompanyService()).GetCompInfo(model.JobInfo.CompanyID);
这段代码是一个控制器动作中的一段代码。代码很简单,就是当model.JobInfo == null时直接跳转到首页,而不再执行这个控制器动作的后续代码。然而我在看错误日志的时候却看到了执行这个页面时提示未将对象引用设置到对象的实例。通过错误重现,发现 model.CompInfo = (new CompanyService()).GetCompInfo(model.JobInfo.CompanyID);在这行报的这个错。刚开始是以为GetCompInfo这个函数有问题,可是通过输出中间变量发现根本就没进入到这个函数就报错了。后来在model.CompInfo = (new CompanyService()).GetCompInfo(model.JobInfo.CompanyID);这行之前添加了一行代码:EventLog.WriteLog(“” + (model.JobInfo == null));居然输出的是true。我晕,这不意味着程序虽然执行了Response.Redirect(“/”, true);跳转,但是后续代码还是执行了。以前处理过类似问题。知道这个函数:
public void RedirectUrl(string url)
{
Response.Clear();//这里是关键,清除在返回前已经设置好的标头信息,这样后面的跳转才不会报错
Response.BufferOutput = true;//设置输出缓冲
EventLog.WriteLog(“” + Response.IsRequestBeingRedirected);
if (!Response.IsRequestBeingRedirected) //在跳转之前做判断,防止重复
{
Response.Redirect(url, true);

  }

}
可以解决此问题。高兴的用RedirectUrl(”/”)换掉Response.Redirect(“/”, true)后,以为问题会解决。可是通过检查日志输出,问题依然存在。
最终使用return RedirectToAction(“index”, “home”);替换 Response.Redirect(“/”, true)才解决此问题。
发现在mvc中使用Response.Redirect做跳转很令人蛋疼。容易出现虽然跳转能够成功,但是后续代码还会执行的情况。只是用return RedirectToAction(“index”, “home”)这种做跳转我以前也遇到过后续代码还会执行的情况。换Response.Redirect(url, true)这种解决了问题。有点晕,原来的return RedirectToAction(“index”, “home”)这种有问题的相关代码找不到了。否则可以好好比较下,到底问题出现在哪里。先放这里吧

0 0
原创粉丝点击