Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the entire HttpResponseMessage serialized?

Why does this Web API implementation

[HttpGet("hello")]
public HttpResponseMessage Hello()
{
    var res = new HttpResponseMessage(HttpStatusCode.OK);
    res.Content = new StringContent("hello", Encoding.UTF8, "text/plain");
    return res;
}

return

{
  "Version":{
    "Major":1,
    "Minor":1,
    "Build":-1,
    "Revision":-1,
    "MajorRevision":-1,
    "MinorRevision":-1
  },
  "Content":{
    "Headers":[{
      "Key":"Content-Type",
      "Value":["text/plain; charset=utf-8"]
    }]
  },
  "StatusCode":200,
  "ReasonPhrase":"OK",
  "Headers":[],
  "RequestMessage":null,
  "IsSuccessStatusCode":true
}

instead of

hello

?

How can I make the Web API return an HTTP response like below?

200 OK
Content-Type: text/plain

hello

What I want to do finally is return JSON and other formats with various status codes, so the following code wouldn't help me as an answer.

[HttpGet("hello")]
public string Hello()
{
    return "hello";
}

(I'm new to ASP.NET and other Microsoft technologies.)

like image 708
Takahiko Kawasaki Avatar asked Sep 19 '15 07:09

Takahiko Kawasaki


1 Answers

I had the same happen to me recently. The reason was that, for some reason, there was two references to the System.Net.Http.dll assembly: one from the GAC and one local copy from my project.

It results in an interesting case where the type of HttpResponseMessage you send isn't the same type of HttpResponseMessage ASP.NET expects, and that's why instead on processing the message, it just serializes it as JSON.

The solution I found for this is to install the System.Net.Http package from NuGet, and ensure that the binding redirect is generated correctly on the Web.config, so that only one copy of the dependency is used.

like image 130
Arturo Torres Sánchez Avatar answered Oct 04 '22 22:10

Arturo Torres Sánchez