Return specific HTTP status code in action for GET

2019-07-24 15:49发布

I'm creating REST service using ASP.NET Web API. How can I return 401 status code from action for GET method...

I don't have problem with returning some status code from e.g. POST method, cause I can set the return type to HttpResponseMessage

   public HttpResponseMessage Post(Car car)
    {
        using (var context = new CarEntities())
        {
            ...
            var response = new HttpResponseMessage(HttpStatusCode.Created);
            response.Headers.Location = new Uri(Request.RequestUri, path);
            return response;
        }
    }

However, how can I return the status code for GET method, when the method returns different type than HttpResponseMessage:

public Car Get(int id)
{

    var context = new CarEntities();
    return context.Cars.Where(p => p.id == id).FirstOrDefault();
}

I would like to return e.g. 401 when authorization in this Get method failed

Thanks

1条回答
等我变得足够好
2楼-- · 2019-07-24 16:29

You should throw a HttpResponseException, which allows you to specify the response code, for example:

if (authFailed) {
    throw new HttpResponseException(HttpStatusCode.Unauthorized);
}
查看更多
登录 后发表回答