HttpResponseMessage r = new HttpResponseMessage();
r.StatusCode = HttpStatusCode.OK;
r.ReasonPhrase = "SUCCESS";
现在如何将
HttpResponseMessage
类的客户对象传递给客户端?一种方法是
return Request.CreateResponse(HttpStatusCode.OK, customers);
假设如果我不希望以这种方式返回响应
Request.CreateResponse(HttpStatusCode.OK, customers);
,而我想创建HttpResponseMessage
的实例并初始化一些属性,然后返回。所以告诉我,我可以通过HttpResponseMessage class
将客户对象传递给客户端吗? 最佳答案
简单的方法是您应该根据请求创建响应:
return Request.CreateResponse(HttpStatusCode.OK, customers);
因为在后台,此方法将为您处理内容协商,而您并不在乎。否则,您必须手动处理以下代码:
IContentNegotiator negotiator = this.Configuration.Services.GetContentNegotiator();
ContentNegotiationResult result = negotiator.Negotiate(
typeof(Customer), this.Request, this.Configuration.Formatters);
var response = new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = new ObjectContent<Customer>(customer,
result.Formatter, result.MediaType)
};
return response;