Asp.Net : Web service throws "Thread was being aborted"
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)
{
开发者_JAVA技巧 HttpContext.Current.Response.StatusCode = 403;
HttpContext.Current.Response.End();
}
/* Do stuff that should not execute unless the user is logged in... */
...
}
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:
- For Response.End, call the HttpContext.Current.ApplicationInstance.CompleteRequest method instead of Response.End to bypass the code execution to the Application_EndRequest event.
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;
}
}
精彩评论