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?