How do I prevent ReadAsStringAsync returning a doubly escaped string?

     [HttpPost]
     public async Task<string> Post(Thing thing)
     {
         var content = "\r";
         var httpResponseMessage = Request.CreateResponse(HttpStatusCode.Accepted, content);
         var escapedString = await httpResponseMessage.Content.ReadAsStringAsync();
         return Content(escapedString, "application/json");            
     }  

I know that I'm probably going to cause 70 bajillion lines of code to execute by doing this (sorry Darrel Miller) but I found that it was just as effective, and less disruptive to my chosen development pattern to use this:

response.Content.ReadAsAsync<string>().Result;

or

await response.Content.ReadAsAsync<string>();

instead of this (that escapes the quotes):

response.Content.ReadAsStringAsync().Result;

Note: the ReadAsAsync is an extension method in the System.Net.Http.HttpContentExtensions, in the System.Net.Http.Formatting assembly. If it's not available in your project, you can add the NuGet package Microsoft.AspNet.WebApi.Client.


It is doing what it is doing because you are cracking an egg with a sledgehammer.

When you call Request.CreateResponse<string>(HttpStatusCode statusCode, T value) you are telling web API that you would like your value serialized using one of the media type formatters. So Web API stuffs your value into an instance of ObjectContent does a whole slew of conneg code, and determines that it can use Formatter X to serialize your "object".

Chances are it is the JSONSerializer that is doing its best to try an return you the string it thinks you want rather than the CR character.

Anyway you can cut to the chase and avoid executing 70 bajillion lines of code by using the HttpContent object that is designed for sending simple strings over the wire.

[HttpPost]
public ResponseMessageResult Post(Thing thing)
{
    var content = "\r";
    var httpResponseMessage = new HttpResponseMessage(HttpStatusCode.Accepted) {
      RequestMessage = Request,
      Content = new StringContent(content)
    };
    return ResponseMessage(httpResponseMessage);
}

In my specific scenario, facing the same issue & in the hope it might help others, it was caused by unneccessarily adding the line

httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

to my code. Removing this line in my Azure Function got rid of the double escaped.