我使用C#
对Web API 2
网络服务进行编码,如果客户未获得授权,我希望能够向客户端发送StatusCode
Unauthorized
正确的凭据。
以下是ApiController
过滤器代码:
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;
}
}
}
以下是HttpClient
代码:
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;
}
}
}
}
}
当IsAuthorized
函数返回false
时,httpResponseMessage
对象设置为HttpClient
仍然返回StatusCode
200,而不是{ 401的{1}}。
我可以帮助将StatusCode
的401返回StatusCode
吗?
答案 0 :(得分:1)
if (response.StatusCode == HttpStatusCode.OK)
{
response.StatusCode == HttpStatusCode.OK;
return response;
}
else
{
throw new HttpResponseException(
Request.CreateErrorResponse(HttpStatusCode.Unauthorized, myCustomMessage));
}
可能重复: How do you return status 401 from WebAPI to AngularJS and also include a custom message?
答案 1 :(得分:0)
查看.Net&#39; JsonResult
然后您可以像这样返回Task<IHttpActionResult>
......
if (response.StatusCode == HttpStatusCode.OK)
{
return Ok();
}
else
{
return Unauthorized();
}