views:

224

answers:

2

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... */
    ...
}
+2  A: 

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.
Matthew Jones
+2  A: 

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;
    }
}
Nick Craver
Will I throw an error if I return null on a non nullable type?
Master Morality
@Master - It shouldn't let you compile that, but you can throw `default(typeHere)` to be safe.
Nick Craver