【问题标题】:Return specific HTTP status code in action for GET request为 GET 请求返回特定的 HTTP 状态代码
【发布时间】:2012-03-24 14:25:42
【问题描述】:

我正在使用 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;
        }
    }

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

public Car Get(int id)
{

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

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

谢谢

【问题讨论】:

  • 我在操作中看不到任何身份验证。这种身份验证会发生在哪里?如果您需要在多个操作中执行此操作,我可能会考虑使用身份验证属性并根据需要装饰操作?

标签: asp.net asp.net-mvc asp.net-web-api


【解决方案1】:

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

if (authFailed) {
    throw new HttpResponseException(HttpStatusCode.Unauthorized);
}

【讨论】:

    猜你喜欢
    • 2021-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多