首页 文章

返回HttpResponseMessage的Web API最佳方法

提问于
浏览
28

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

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

No errors:

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

Any error or fail

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

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

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

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

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

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

3 回答

  • 33

    虽然这不是直接回答这个问题,但我想提供一些我认为有用的信息 . 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);
     }
    

    然后,您可以封装以创建自定义的 . How to set custom headers when using IHttpActionResult?

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

    它可能非常类似于使用旧的 .

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

    return BadRequest("Custom Message Here");
    

    您不能与许多其他的一起执行此操作,但有助于您要发回的常见消息 .

  • 2

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

    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状态代码 .

  • 4

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

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

相关问题