开发者

Asp.Net : Web service throws "Thread was being aborted"

开发者 https://www.devze.com 2022-12-26 01:54 出处:网络
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 Resp

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:

  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.


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;
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消