【发布时间】: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。
- 我应该使用什么 HttpStatusCode?li>
- 是否应该用缺少的参数名称覆盖默认的 ReasonPhase 值?
- 处理 API 控制器函数中抛出的异常并告知客户端的最佳做法是什么?
【问题讨论】:
-
返回任何有意义的 HTTP 状态。对于参数错误,我通常返回 400,Bad Request。
-
错误请求是一个好请求。 msdn.microsoft.com/en-us/library/…
标签: c# asp.net-web-api