【问题标题】:What HttpStatusCode and ReasonPhase in Web API to return for defensive programming?Web API 中的 HttpStatusCode 和 ReasonPhase 为防御性编程返回什么?
【发布时间】:2015-08-19 21:05:59
【问题描述】:

在编写公共函数时,我通常会遵循防御性编程的做法,像这样。

    public long CreateSection(Section section)
    {
        if (section == null)
            throw new ArgumentNullException("section");

        var entityId = section.EntityId;
        if (entityId == 0)
            throw new ArgumentException("To add section, the entity must have already been saved with entityId", "section");

        Debug.Assert(section.Id == 0, "If someone give such section, I don't minid to save it.");

        ...
        return section.Id;
    }

我将把它封装到一个 ASP.NET Web API 2.x 函数中。在 ArgumentExceptions 上,我认为我需要使用 HttpStatusCode 和 ReasonPhase 抛出 HttpResponseException。

  1. 我应该使用什么 HttpStatusCode?​​li>
  2. 是否应该用缺少的参数名称覆盖默认的 ReasonPhase 值?
  3. 处理 API 控制器函数中抛出的异常并告知客户端的最佳做法是什么?

【问题讨论】:

标签: c# asp.net-web-api


【解决方案1】:

个人意见,

  1. 我会使用 400 错误请求。应该避免 500,因为您应该处理异常,因此它确实不是一个完整的故障。
  2. 是的,让消费者知道他们做错了什么总是好的,这样他们就可以更正他们的下一个请求。如果您的服务一触即发,他们怎么知道自己做错了什么?
  3. 不要扔掉它们。如果你这样做了,请确保你处理它们以输出像旧 ASP 项目中 Global.asax 中的 Application_Error 一样的体面的东西。毕竟,干净的 500 次故障并不是很漂亮:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多