我正在考虑创建一个REST WebAPI,并希望将“错误”消息与我的状态代码一起返回 - 作为终端客户端关于出错的原因。
其中一个回复将是422状态代码 - 但我无法看到如何将数据元素纳入我的响应中?
public HttpResponseMessage GetValidate(string number)
{
var response = Request.CreateResponse((HttpStatusCode)422);
response.Content new { error = "something wrong here", item = "number" }; // This is wrong!
return response;
}
答案 0 :(得分:1)
HttpStatusCode
代码中没有422
的定义。看看documentation。
您可以使用500 http状态代码Interval Error
:
return Request.CreateResponse(HttpStatusCode.InternalServerError, new {error = "something wrong here", item = "number"});
或400 Bad Request
:
return Request.CreateResponse(HttpStatusCode.BadRequest, new { error = "something wrong here", item = "number" });
答案 1 :(得分:0)
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "message");
或其他重载。
答案 2 :(得分:0)
IETF有一个提案草案,提供从API返回错误信息的标准方法。详情请见http://tools.ietf.org/html/draft-nottingham-http-problem-04
我有一个支持在Nuget和GitHub project上创建此格式的库。
就像这样......
var problem = new ProblemDocument
{
ProblemType = new Uri("http://example.org"),
Title = "Houston we have a problem",
StatusCode = HttpStatusCode.BadGateway,
ProblemInstance = new Uri("http://foo")
};
problem.Extensions.Add("bar", new JValue("100"));
var response = new HttpResponseMessage(HttpStatusCode.BadGateway)
{
Content = new ProblemContent(problem)
};