在 WebMethod 中未正确捕获 ThreadAbortException

ThreadAbortException not catched properly in WebMethod

我必须从 WebMethod 重定向,我知道我不能。所以我只是想 return 页面 url 作为字符串并将在 success 回调中重定向。

问题是我在重定向之前有大量的代码,并且是用一个集中的方法编写的(只有在重定向之前调用的方法才能在此之前执行相同的操作。)在我的重定向中,我也必须调用该函数.

我只是把我的代码放在这里,没有调用集中函数以便更好地理解。

    [WebMethod]
    [ScriptMethod(UseHttpGet = true)]
    public static string TestException()
    {
        try
        {
            System.Web.HttpContext.Current.Response.Redirect("Test.aspx");
            return "No Exception";
        }
        catch(Exception ex)
        {
            return "Exception";
        }

    }

作为回应,我得到 Internal Server Error (505)System.Threading.ThreadAbortException 而不是 returning "Exception" 就像在 catch 块中一样。

其他例外情况并非如此,即如果我将 Response.Redirect 替换为

int i = 0;
int j = 5/i;

它也会引发异常,但不会给我 Internal Server Error (505),而是 return "Excetion" 即 return 来自 catch 块的字符串。

我的问题是

  1. 为什么它对待 System.Threading.ThreadAbortException 不同于其他异常?
  2. 我知道其他解决方法,比如函数重载和在 Centralized 函数中使用的可选参数,通过检查附加参数我可以 return 字符串而不是重定向,但我想知道是否有有什么我可以在 webmethod 或任何其他地方使用而无需触及集中功能来使其工作的东西吗?

Why it is treating System.Threading.ThreadAbortException differently from other exceptions?

关于您的第一个问题,来自 MSDN 上的 ThreadAbortException

ThreadAbortException is a special exception that can be caught, but it will automatically be raised again at the end of the catch block. When this exception is raised, the runtime executes all the finally blocks before ending the thread. Because the thread can do an unbounded computation in the finally blocks or call Thread.ResetAbort to cancel the abort, there is no guarantee that the thread will ever end. If you want to wait until the aborted thread has ended, you can call the Thread.Join method. Join is a blocking call that does not return until the thread actually stops executing.

我认为要防止这种情况发生,您需要在 catch 块中调用 Thread.ResetAbort()

[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static string TestException()
{
    try
    {
        System.Web.HttpContext.Current.Response.Redirect("Test.aspx");
        return "No Exception";
    }
    catch(ThreadAbortException ex)
    {
        Thread.ResetAbort();
        return "Exception";
    }

}

并且在 WEB METHOD 中使用 Response.Redirect 不是一个好习惯!当您使用 WEB METHOD 时,您应该遵循 SOAP 规则。你需要知道调用 Response.Redirect 会调用 Response.End.

HttpResponse.Redirect Method MSDN 页面:

An absolute URL (for example, http://www.contoso.com/default.aspx) or a relative URL (for example, default.aspx) can be specified for the target location but some browsers may reject a relative URL. Redirect calls End which raises a ThreadAbortException exception upon completion.