Asp.Net web service: I would like to return error 403 forbidden

I have got a web service programmed in c# / asp.net.

[WebService(Namespace = "http://example.com/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
[System.ComponentModel.ToolboxItem(false)]
public class Service: System.Web.Services.WebService
{

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public Result GetData()
    {
        User user = GetUser();

        if (user.LoggedIn)
        {
            return GetData();
        }
        else
        {
            // raise exception -> return error 403
        }
    }

How is it possible to return error 403 out of this web service? I can throw an exception - but this shows the exeption and not his error.

Any ideas?


If you were using MVC you'd do the following:

            return new HttpStatusCodeResult(HttpStatusCode.Forbidden);

You don't need to set both Context.Response.Status and Context.Response.StatusCode. Simply setting

Context.Response.StatusCode = (int)System.Net.HttpStatusCode.Forbidden

will automatically set Response.Status for you.


To answer the question completely - this is the code I've used (thank you strider for more information):

[WebService(Namespace = "http://example.com/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
[System.ComponentModel.ToolboxItem(false)]
public class Service: System.Web.Services.WebService
{

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public Result GetData()
    {
        User user = GetUser();

        if (user.LoggedIn)
        {
            return GetData();
        }
        else
        {
            Context.Response.Status = "403 Forbidden"; 
            //the next line is untested - thanks to strider for this line
            Context.Response.StatusCode = 403;
            //the next line can result in a ThreadAbortException
            //Context.Response.End(); 
            Context.ApplicationInstance.CompleteRequest(); 
            return null;
        }
    }

You can protect all your methods by placing the code in your WebService constructor. This prevents your WebMethod from even being called:

public Service(): base()
{
    if (!GetUser().LoggedIn)
    {
        Context.Response.StatusCode = (int)System.Net.HttpStatusCode.Forbidden;
        Context.Response.End();
    }
}

In Asp.Net Web Api 2, you'd use:

return new StatusCodeResult(HttpStatusCode.Forbidden, this);