lzl124631x
lzl124631x

Reputation: 4809

Request.CreateResponse versus response.Content?

My code was

var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(
                             JsonConvert.SerializeObject(data),
                             Encoding.UTF8, "application/json");
return response;

and it works fine by returning some json data.

Later I noticed that Request.CreateResponse() can accept a second parameter T value with the value being the content of the HTTP response message. So I tried to compress the above three lines into one line

return Request.CreateResponse(
             HttpStatusCode.OK, new StringContent(JsonConvert.SerializeObject(data), 
             Encoding.UTF8, "application/json"));

But it doesn't work as expected. It returns

{
  "Headers": [
    {
      "Key": "Content-Type",
      "Value": [
        "application/json; charset=utf-8"
      ]
    }
  ]
}

Did I misunderstand the second parameter of Request.CreateResponse()?

Upvotes: 2

Views: 3042

Answers (1)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149598

Did I misunderstand the second parameter of Request.CreateResponse()

Yes, you have. The second parameter is simply the value itself. You're passing StringContent as T value, instead of letting the CreateResponse serialize it for you with the proper content type you pass. The reason you see no data is because CreateResponse probably doesn't understand how to properly serialize an object of type StringContent.

All you need is:

return Request.CreateResponse(HttpStatusCode.OK, data, "application/json"));

Upvotes: 3

Related Questions