Asp.Net: web service throws "Thread has been interrupted"
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 it is not, however when I call Response.End()
I get the "Thread was aborted" error. 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... */
...
}
source to share
Since this is a WebMethod
, the simplest method is to simply return nothing. This would be the equivalent behavior to complete the ajax request response:
[WebMethod(true)]
public string MyMethod()
{
if(!userIsLoggedIn)
{
HttpContext.Current.Response.StatusCode = 403;
return null;
}
}
source to share
From the MS Support Page :
If you use the Response.End, Response.Redirect, or Server.Transfer method, a ThreadAbortException is thrown. You can use try-catch to catch this exception.
This behavior is by design.
To work around this issue, use one of the following methods:
- For Response.End, call HttpContext.Current.ApplicationInstance.CompleteRequest instead of Response.End to bypass the Application_EndRequest event code execution.
source to share