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
将客户对象传递给客户端吗?
答案 0 :(得分:4)
简单的方法是根据请求创建响应:
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;