如何从Web服务将statusCode返回给客户端?

时间:2016-02-09 07:18:47

标签: c# asp.net-web-api2 http-response-codes

我使用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吗?

2 个答案:

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