Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I prevent ReadAsStringAsync returning a doubly escaped string?

I have a Web API method that looks a bit like this:

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

In some other client code, when I call:

    var content = httpResponseMessage.Content.ReadAsStringAsync().Result; 

content is:

    "\\r" 

but I would like it to remain as the original:

    "\r" 

why is the client receiving a doubly escaped string and how can I prevent it happening?

like image 401
Grokodile Avatar asked Nov 05 '13 13:11

Grokodile


2 Answers

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.

like image 104
Josh Avatar answered Oct 14 '22 08:10

Josh


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); } 
like image 40
Darrel Miller Avatar answered Oct 14 '22 10:10

Darrel Miller