Simon
Simon

Reputation: 8345

How do I return a statusCode to the client from a web service?

I am coding a C# webservice using Web API 2 and I would like to be able to send a StatusCode of Unauthorized to the client if the client is not authorized with the correct credentials.

Here is the ApiController filter code:

public class ApiAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool IsAuthorized(HttpActionContext actionContext)
    {
        if (HttpContext.Current.User.Identity.IsAuthenticated)
        {
            return true;
        }
        else
        {
            var httpResponseMessage = new HttpResponseMessage();
            httpResponseMessage.StatusCode = System.Net.HttpStatusCode.Unauthorized;
            actionContext.Response = httpResponseMessage;
            return false;
        }
    }
}

Here is the HttpClient code:

private async Task<bool> RequestAuthorizeAsync(string serverAddress)
{
    using (HttpClient client = new HttpClient())
    {
        using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, serverAddress))
        {
            request.Headers.Authorization = null;
            using (HttpResponseMessage response = await client.SendAsync(request))
            {
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
    }
}

When the IsAuthorized function returns false, with the httpResponseMessage object set, the HttpClient is still returning a StatusCode of 200, and not the StatusCode of 401.

Can I please have some help with returning a StatusCode of 401 to the HttpClient?

Upvotes: 2

Views: 3319

Answers (2)

adrian3martin
adrian3martin

Reputation: 101

Check out .Net's JsonResult

Then you can just return a Task<IHttpActionResult> like so...

            if (response.StatusCode == HttpStatusCode.OK)
            {
                return Ok();
            }
            else
            {
                return Unauthorized();
            }

Upvotes: 0

jolySoft
jolySoft

Reputation: 3020

if (response.StatusCode == HttpStatusCode.OK)
                {
                    response.StatusCode == HttpStatusCode.OK;
                    return response;
                }
                else
                {
                    throw new HttpResponseException(
     Request.CreateErrorResponse(HttpStatusCode.Unauthorized, myCustomMessage));
                }

Possible duplicate: How do you return status 401 from WebAPI to AngularJS and also include a custom message?

Upvotes: 2

Related Questions