返回HttpResponseMessage的Web API最佳方法

我有一个Web API项目,我的方法总是返回HttpResponseMessage

所以,如果它工作或失败我返回:

没有错误:

return Request.CreateResponse(HttpStatusCode.OK,"File was processed."); 

任何错误或失败

 return Request.CreateResponse(HttpStatusCode.NoContent, "The file has no content or rows to process."); 

当我返回一个对象然后我使用:

 return Request.CreateResponse(HttpStatusCode.OK, user); 

我想知道如何向HTML5客户端返回更好的封装respose,以便我可以返回有关事务的更多信息等。

我在考虑创建一个可以封装HttpResponseMessage但也有更多数据的自定义类。

有没有人实现类似的东西?

虽然这不是直接回答这个问题,但我想提供一些我觉得有用的信息。 http://weblogs.asp.net/dwahlin/archive/2013/11/11/new-features-in-asp-net-web-api-2-part-i.aspx

HttpResponseMessage或多或少被IHttpActionResult取代。 它更清洁,更容易使用。

 public IHttpActionResult Get() { Object obj = new Object(); if (obj == null) return NotFound(); return Ok(obj); } 

然后,您可以封装以创建自定义的。 使用IHttpActionResult时如何设置自定义标头?

我还没有找到实现自定义结果的需求,但是当我这样做时,我将会走这条路。

它可能与使用旧的非常相似。

进一步扩展这一点并提供更多信息。 您还可以包含带有某些请求的消息。 例如。

 return BadRequest("Custom Message Here"); 

你不能用其他许多方法做到这一点,但有助于你想要发回的常见消息。

您可以返回错误响应以提供更多详细信息。

 public HttpResponseMessage Get() { HttpError myCustomError = new HttpError("The file has no content or rows to process.") { { "CustomErrorCode", 42 } }; return Request.CreateErrorResponse(HttpStatusCode.BadRequest, myCustomError); } 

会回来:

 { "Message": "The file has no content or rows to process.", "CustomErrorCode": 42 } 

更多细节在这里: http : //blogs.msdn.com/b/youssefm/archive/2012/06/28/error-handling-in-asp-net-webapi.aspx

我还使用http://en.wikipedia.org/wiki/List_of_HTTP_status_codes来帮助我确定要返回的http状态代码。

一个重要的注意事项:不要在204个回复中添加内容! 它不仅违反了HTTP规范,而且如果你这样做,.NET实际上可能会出现意外行为。

我错误地使用了return Request.CreateResponse(HttpStatusCode.NoContent, null); 这导致了真正的头痛; 来自同一会话的未来请求将由于在响应之前具有"null"字符串值而中断。 我想.NET并不总是完全清楚来自同一会话的API调用的响应对象。