返回GET请求的特定HTTP状态代码

Bar*_*art 2 asp.net asp.net-mvc asp.net-web-api

我正在使用ASP.NET Web API创建REST服务.如何从GET方法的操作中返回401状态代码...

我没有从POST方法返回一些状态代码的问题,因为我可以将返回类型设置为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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

但是,当方法返回的类型不同于HttpResponseMessage时,如何返回GET方法的状态代码:

public Car Get(int id)
{

    var context = new CarEntities();
    return context.Cars.Where(p => p.id == id).FirstOrDefault();
}
Run Code Online (Sandbox Code Playgroud)

当此Get方法中的授权失败时,我想返回例如401

谢谢

Jon*_*Jon 5

你应该抛出一个HttpResponseException允许你指定响应代码的,例如:

if (authFailed) {
    throw new HttpResponseException(HttpStatusCode.Unauthorized);
}
Run Code Online (Sandbox Code Playgroud)