WebAPI HttpResponse消息

时间:2015-03-31 19:14:59

标签: asp.net-web-api2

对于WebAPI2 Action结果,HTTPResponseMessage用作返回类型之一,Request.CreateResponse用于返回消息。

当我们想要返回模型的单个实例但是如果我们想要从“模型”返回多行时,Request.CreateResponse很方便,Request.CreateResponse或Request.CreateResponse没有重载方法支持它(如就我所读)。如果有人可以发布样本,那就太棒了

另外,我几乎没有其他疑问。

•为什么我们必须使用HttpResponseMessage而不是IQueryable或Model返回类型? •Request.CreateResponse和Request.CreateResponse之间有什么区别,因为我们能够使用两种方法返回模型的单个实例。我们如何从两者中选择一个?

1 个答案:

答案 0 :(得分:0)

您可以将操作方法​​的返回类型设置为任何可序列化数据。内容协商和格式化程序会将返回的值转换为HTTP响应。

来自Action Results in Web API 2

  

其他退货类型

     

对于所有其他返回类型,Web API使用media formatter来序列化返回值。 Web API将序列化值写入响应主体。响应状态代码为200(OK)。

public class ProductsController : ApiController
{
    public IEnumerable<Product> Get()
    {
        return GetAllProductsFromDB();
    }
}
     

此方法的缺点是您无法直接返回错误代码,例如404.但是,您可以为错误代码抛出HttpResponseException。有关详细信息,请参阅Exception Handling in ASP.NET Web API

     

Web API使用请求中的Accept标头来选择格式化程序。有关详细信息,请参阅Content Negotiation

     

示例请求:

GET http://localhost/api/products HTTP/1.1
User-Agent: Fiddler
Host: localhost:24127
Accept: application/json
     

回复示例:

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/8.0
Date: Mon, 27 Jan 2014 08:53:35 GMT
Content-Length: 56

[{"Id":1,"Name":"Yo-yo","Category":"Toys","Price":6.95}]