【问题标题】:Equivalent of Request.CreateResponse()等效于 Request.CreateResponse()
【发布时间】:2014-02-24 19:27:03
【问题描述】:

什么等价于

var newOrder = new OrderViewModel()
{

   Id = orderDetails.Id,
   Name = orderDetails.Service.Name,
   .....
};

Request.CreateResponse(HttpStatusCode.OK, newOrder);

采用这种格式:

HttpResponseMessage response = new HttpResponseMessage();
response.StatusCode = HttpStatusCode.OK;
response.ReasonPhrase = "successfully created blablabla";

在Request.CreateResponse() 中我可以传递一个对象。我如何使用HttpResponseMessage 做到这一点?

也希望能够传递消息(例如 ReasonPhrase),但不能使用 Request.CreateResponse() 传递消息。或者我错过了什么。

【问题讨论】:

    标签: c# asp.net-web-api httpresponse


    【解决方案1】:

    要将对象作为响应内容传入,您可以构造ObjectContent<T>:

    response.Content = new ObjectContent<OrderViewModel>(newOrder, 
                                             new JsonMediaTypeFormatter())
    

    ObjectContent的其他构造函数:

    http://msdn.microsoft.com/en-us/library/hh835040(v=vs.118).aspx

    【讨论】:

    • 顺便问一下乔安娜,Request.CreateResponse() 方法是否也支持像 response.ReasonPhrase 这样的自定义消息?看文档告诉我没有。也许我错过了什么。
    • @Quoter - 我不知道。您可能需要创建自己的扩展程序。
    猜你喜欢
    • 2020-06-22
    • 2019-06-29
    • 2021-09-22
    • 2017-06-05
    • 2012-10-21
    • 2018-10-05
    • 2017-08-02
    • 2012-03-31
    • 2018-01-28
    相关资源
    最近更新 更多