Asp.Net web service: I would like to return error 403 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.


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();
    }
}

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

            return new HttpStatusCodeResult(HttpStatusCode.Forbidden);

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