编程语言
首页 > 编程语言> > c# – 在ASP代码隐藏中,重定向后添加return关键字有什么好处?

c# – 在ASP代码隐藏中,重定向后添加return关键字有什么好处?

作者:互联网

我想知道是否有必要在我的Codebehind中的Response.RedirectPermanent调用之后保留一个return语句?它似乎不是,但我想与其他人确认.

Response.RedirectPermanent(vpd.VirtualPath);
return;

是否有任何理由这样做是为了获得功能还是性能提升?

解决方法:

回答大修:

拿着电话!我之前的答案中的细节是在进一步研究之后,完全没有.实际上,MSDN文档指定了以下内容:

When you use this method in a page handler to terminate a request for one page and start a new request for another page, set endResponse to false and then call the CompleteRequest method. If you specify true for the endResponse parameter, this method calls the End method for the original request, which throws a ThreadAbortException exception when it completes. This exception has a detrimental effect on Web application performance, which is why passing false for the endResponse parameter is recommended.

http://msdn.microsoft.com/en-GB/library/a8wa7sdt.aspx

因此,实际上,页面的其余部分没有被执行(理论上 – 请参阅下面的“更新”以获取何时崩溃的示例);然而,按照你的方式执行它仍然是一个非常明显的问题,即endResponse机制是通过抛出ThreadAbortException来实现的,这是一种终止当前线程处理的相对昂贵的方法.

相反,你应该告诉它让线程继续,但立即返回 – 同时确保调用堆栈中的其他方法正在做他们应该做的事情:

Response.RedirectPermanent(vpd.VirtualPath, false);
return;

更好的是,在条件中包装调用以确保不会调用不需要的代码然后使用CompleteRequest方法(它不会终止当前正在执行的代码但会绕过所有后续事件):

if (_redirecting)
{
    Response.RedirectPermanent(vpd.VirtualPath, false);
    Context.ApplicationInstance.CompleteRequest();
}
else
{
    /* Code I don't want to execute if I do a redirect */
    DeleteUsersDataForever(_currentUser);
}

关于这个主题here有一篇深入的文章,甚至文档本身似乎也有一个unhealthy distaste for the HttpResponse.End method,如果你允许Response.Redirect为你做响应终止,这就是所谓的.

更新:此外,鉴于通过引发异常终止线程,请考虑如果您尝试在try / catch中进行重定向会发生什么:

try
{
    // Redirect and terminate execution
    Response.Redirect(someUrl, true);
}
catch
{
    // Handle some errors.
}

DeleteUsersDataForever(_currentUser);

Response.End引发的异常会在catch块中捕获.因此,您的其余代码仍然执行,并且您不小心删除了所有_currentUser的数据(除非您在catch块中执行某些操作来阻止此操作,例如将异常冒泡到调用方).

标签:c,asp-net,return,response-redirect,server-transfer
来源: https://codeday.me/bug/20190529/1178523.html