Asp.Net : Web service throws “Thread was being aborted”

懵懂的女人 提交于 2020-01-05 01:08:52

问题


I have a web service that I call via ajax that requires the user to be logged in. in each method I want to check if the user is logged in and send a 403 code if they are not, however when I call a Response.End() I get the error "Thread was being aborted". What should I call instead?

[WebMethod(true)]
public string MyMethod()
{
    if(!userIsLoggedIn)
    {
            HttpContext.Current.Response.StatusCode = 403;
            HttpContext.Current.Response.End();
    }
    /* Do stuff that should not execute unless the user is logged in... */
    ...
}

回答1:


Since it's a WebMethod, the easiest method is to just return nothing. This would be equivalent behavior to ending the response for an ajax request:

[WebMethod(true)]
public string MyMethod()
{
    if(!userIsLoggedIn)
    {
       HttpContext.Current.Response.StatusCode = 403;
       return null;
    }
}



回答2:


From the MS Support issue page:

If you use the Response.End, Response.Redirect, or Server.Transfer method, a ThreadAbortException exception occurs. You can use a try-catch statement to catch this exception.

This behavior is by design.

To work around this problem, use one of the following methods:

  1. For Response.End, call the HttpContext.Current.ApplicationInstance.CompleteRequest method instead of Response.End to bypass the code execution to the Application_EndRequest event.


来源:https://stackoverflow.com/questions/2610907/asp-net-web-service-throws-thread-was-being-aborted

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!