简体   繁体   English

Web API 返回 HttpResponseMessage 的最佳方法

[英]Web API Best Approach for returning HttpResponseMessage

I have a Web API project and right my methods always returns HttpResponseMessage .我有一个 Web API 项目,我的方法总是返回HttpResponseMessage

So, if it works or fails I return:所以,如果成功或失败,我会返回:

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.");

When I return an object then I use:当我返回 object 时,我使用:

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

I would like to know how can I return to my HTML5 client a better encapsulated respose, so I can return more information about the transaction, etc.我想知道如何向我的 HTML5 客户端返回一个更好的封装响应,以便我可以返回有关交易等的更多信息。

I was thinking on creating a custom class that can encapsulate the HttpResponseMessage but also have more data.我正在考虑创建一个自定义 class ,它可以封装 HttpResponseMessage 但也有更多数据。

Does anyone have implemented something similar?有没有人实施过类似的东西?

Although this is not directly answering the question, I wanted to provide some information I found usefull. 虽然这不是直接回答这个问题,但我想提供一些我认为有用的信息。 http://weblogs.asp.net/dwahlin/archive/2013/11/11/new-features-in-asp-net-web-api-2-part-i.aspx http://weblogs.asp.net/dwahlin/archive/2013/11/11/new-features-in-asp-net-web-api-2-part-i.aspx

The HttpResponseMessage has been more or less replaced with IHttpActionResult. HttpResponseMessage或多或少被IHttpActionResult取代。 It is much cleaner an easier to use. 它更清洁,更容易使用。

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

Then you can encapsulate to create custom ones. 然后,您可以封装以创建自定义的。 How to set custom headers when using IHttpActionResult? 使用IHttpActionResult时如何设置自定义标题?

I haven't found a need yet for implementing a custom result yet but when I do, I will be going this route. 我还没有找到实现自定义结果的需求,但是当我这样做时,我将会走这条路。

Its probably very similar to do using the old one as well. 它可能非常类似于使用旧的。

To expand further on this and provide a bit more info. 进一步扩展这一点并提供更多信息。 You can also include messages with some of the requests. 您还可以包含包含某些请求的消息。 For instance. 例如。

return BadRequest("Custom Message Here");

You can't do this with many of the other ones but helps for common messages you want to send back. 您不能与许多其他的一起执行此操作,但有助于您要发回的常见消息。

You can return an error response to provide more detail. 您可以返回错误响应以提供更多详细信息。

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

Would return: 会回来:

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

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

I also use http://en.wikipedia.org/wiki/List_of_HTTP_status_codes to help me determine what http status code to return. 我还使用http://en.wikipedia.org/wiki/List_of_HTTP_status_codes来帮助我确定要返回的http状态代码。

One important note: Don't put content in 204 responses! 一个重要的注意事项:不要在204个回复中添加内容! Not only is it against the HTTP specification, but .NET can actually behave in unexpected manners if you do. 它不仅违反了HTTP规范,而且如果你这样做,.NET实际上可能会出现意外行为。

I mistakenly used return Request.CreateResponse(HttpStatusCode.NoContent, null); 我错误地使用了return Request.CreateResponse(HttpStatusCode.NoContent, null); and it led to a real headache; 它导致了真正的头痛; future requests from the same session would break due to having a "null" string value prepended to the response. 来自同一会话的未来请求将由于在响应之前加上"null"字符串值而中断。 I guess .NET doesn't always do a full clear of the response object for API calls from the same session. 我想.NET并不总是完全清楚来自同一会话的API调用的响应对象。

I'm learning so don't what I'm about to say may be silly (or not).我正在学习,所以不要说我要说的是愚蠢的(或不是)。

Why not create a class/model for your APIResponse?为什么不为您的 APIResponse 创建一个类/模型? Something like:就像是:

 public class APIResponse
    {
        public HttpStatusCode StatusCode { get; set; }
        public bool IsSuccess { get; set; } = true;
        public List<string> Messages { get; set; }
        public object Object { get; set; }
    }

Then you have a standard response easier to read and you can always add more information if you need to.这样您就有了一个更易于阅读的标准回复,而且如果需要,您可以随时添加更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM