title: C# string encoding issue via mocked HttpResponseMessage
body: <p>I am trying to test fetching data from a remote API. I setup the HttpClient as follows:</p>
  <pre><code>HttpClient httpClient = SetupHttpClient((HttpRequestMessage request) =&gt;
  {
      FileStream file = new FileStream(&quot;API_Data.json&quot;), FileMode.Open, FileAccess.Read);
      StreamReader sr = new StreamReader(file, true);
      var response = request.CreateResponse(HttpStatusCode.OK, sr.ReadToEnd());
      response.Content.Headers.ContentEncoding.Add(&quot;UTF-8&quot;);
      return Task.FromResult(response);
  });
  </code></pre>
  <p>The <code>SetupHttpClient</code> is not relevant here - what matters is the Response that is delivered, which as you can see is created by creating a StreamReader from a FileStream and reading that Stream into the Response.</p>
  <p>Using the Text Visualizer I can see that the file has been successfully read into the Response Stream and all special chars such as new lines, tabs and double quotes appear correctly, as per this screenshot:</p>
  <p><a href="https://i.stack.imgur.com/RjJfc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RjJfc.png" alt="Hover_Debug_Input" /></a></p>
  <p>On the other end, I fetch the content from the HttpResponseMessage as follows:</p>
  <pre><code>Stream responseStream = await response.Content.ReadAsStreamAsync();
  StreamReader responseReader = null;
  
  if (response.Content.Headers.ContentEncoding.Count &gt; 0)
      responseReader = new StreamReader(responseStream, System.Text.Encoding.GetEncoding(response.Content.Headers.ContentEncoding.First()));
  else
      responseReader = new StreamReader(responseStream, true);
  
  string content = await responseReader.ReadToEndAsync();
  return content;
  </code></pre>
  <p>Hover debugging the response again at this point shows that the data is still OK:</p>
  <p><a href="https://i.stack.imgur.com/od4Uc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/od4Uc.png" alt="enter image description here" /></a></p>
  <p>The Text Visualizer shows exactly the same as in the 1st screenshot above. Here comes the problem - even though the response content is a string, I can't access the Value property and all the retrieval mechanisms that response.Content offers are via Streams. OK fine, so I get the content via a Stream, however after having been through the Stream, all special chars are now double escaped as you can see here:</p>
  <p><a href="https://i.stack.imgur.com/MCdgE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MCdgE.png" alt="enter image description here" /></a>
  <a href="https://i.stack.imgur.com/FVX6c.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FVX6c.png" alt="enter image description here" /></a></p>
  <p>This means that I now have to un-escape all these special chars in order to be able to use the returned string as json - if I don't un-escape it then the JsonDeserializer chokes when I try to deserialize it. The StreamReader also adds a (single-escaped) double-quote as the first and last char for good measure.</p>
  <p>Googling this all I can find are references to using the correct encoding. As such, I ensured that I saved the source file as UTF-8, that I sent 'UTF-8' as the encoding with the HttpResponseMessage (<code>response.Content.Headers.ContentEncoding.Add(&quot;UTF-8&quot;);</code>), and that when decoding the Response 'UTF-8' was again used as the encoding (<code>responseReader = new StreamReader(responseStream, System.Text.Encoding.GetEncoding(response.Content.Headers.ContentEncoding.First()));</code>) - as you can see, this has not achieved the desired effect of obtaining a string which is not double-escaped.</p>
  <p>I don't want to have to do a 'manual' un-escaping of all special chars when I get the response string from the Stream - this is a terrible hack, however it feels like the only option at the minute - either that or use reflection to get the content of the <code>response.Content.Value</code> property if I detect that <code>response.Content</code> is a String - again another hack that I don't want to do.</p>
  <p>How can I ensure that when fetching the <code>response.Content</code> value via a StreamReader that I don't get double-escaped special chars?</p>
  <p>EDIT: For clarity, here is the SetupHttpClient method:</p>
  <pre><code>public HttpClient SetupHttpClient(Func&lt;HttpRequestMessage, Task&lt;HttpResponseMessage&gt;&gt; response)
  {
      var configuration = new HttpConfiguration();
      var clientHandlerStub = new HttpDelegatingHandlerStub((request, cancellationToken) =&gt;
      {
          request.SetConfiguration(configuration);
          return response(request);
      });
  
      HttpClient httpClient = new HttpClient(clientHandlerStub);
      mockHttpClientFactory.Setup(_ =&gt; _.CreateClient(It.IsAny&lt;string&gt;())).Returns(httpClient);
      return httpClient;
  }
  </code></pre>
  <p>and the HttpDelegatingHandlerStub</p>
  <pre><code>public class HttpDelegatingHandlerStub : DelegatingHandler
  {
      private readonly Func&lt;HttpRequestMessage, CancellationToken, Task&lt;HttpResponseMessage&gt;&gt; _handlerFunc;
      public HttpDelegatingHandlerStub()
      {
          _handlerFunc = (request, cancellationToken) =&gt; Task.FromResult(request.CreateResponse(HttpStatusCode.OK));
      }
  
      public HttpDelegatingHandlerStub(Func&lt;HttpRequestMessage, CancellationToken, Task&lt;HttpResponseMessage&gt;&gt; handlerFunc)
      {
          _handlerFunc = handlerFunc;
      }
  
      protected override Task&lt;HttpResponseMessage&gt; SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
      {
          return _handlerFunc(request, cancellationToken);
      }
  }
  </code></pre>
  <p>EDIT2: A minimal, reproducible example - this requires the following packages - Microsoft.AspNet.WebApi.Core, Microsoft.Extensions.Http, Moq:</p>
  <pre><code>using System;
  using System.IO;
  using System.Linq;
  using System.Net;
  using System.Net.Http;
  using System.Threading;
  using System.Threading.Tasks;
  using System.Web;
  using System.Web.Http;
  
  using Moq;
  
  namespace StreamReaderEncoding
  {
      internal class Program
      {
          static Mock&lt;IHttpClientFactory&gt; mockHttpClientFactory;
  
          static void Main(string[] args)
          {
              MainAsync().Wait();
          }
  
          static async Task MainAsync()
          {
              mockHttpClientFactory = new Mock&lt;IHttpClientFactory&gt;();
              string content = @&quot;{
      &quot;&quot;test&quot;&quot;: &quot;&quot;true&quot;&quot;
  }&quot;;
              Console.WriteLine($&quot;content before: {content}&quot;);
  
              HttpClient httpClient = SetupHttpClient((HttpRequestMessage request) =&gt;
              {
                  var stream = new MemoryStream();
                  var writer = new StreamWriter(stream);
                  writer.Write(content);
                  writer.Flush();
                  stream.Position = 0;
  
                  StreamReader sr = new StreamReader(stream, true);
                  var response = request.CreateResponse(HttpStatusCode.OK, sr.ReadToEnd());
                  response.Content.Headers.ContentEncoding.Add(&quot;UTF-8&quot;);
                  return Task.FromResult(response);
              });
  
              HttpResponseMessage response = await httpClient.GetAsync(&quot;https://www.test.com&quot;);
  
              Stream responseStream = await response.Content.ReadAsStreamAsync();
              StreamReader responseReader = null;
  
              if (response.Content.Headers.ContentEncoding.Count &gt; 0)
                  responseReader = new StreamReader(responseStream, System.Text.Encoding.GetEncoding(response.Content.Headers.ContentEncoding.First()));
              else
                  responseReader = new StreamReader(responseStream, true);
  
              content = await responseReader.ReadToEndAsync();
              Console.WriteLine($&quot;content after: {content}&quot;);
          }
  
          static HttpClient SetupHttpClient(Func&lt;HttpRequestMessage, Task&lt;HttpResponseMessage&gt;&gt; response)
          {
              var configuration = new HttpConfiguration();
              var clientHandlerStub = new HttpDelegatingHandlerStub((request, cancellationToken) =&gt;
              {
                  request.SetConfiguration(configuration);
                  return response(request);
              });
  
              HttpClient httpClient = new HttpClient(clientHandlerStub);
              mockHttpClientFactory.Setup(_ =&gt; _.CreateClient(It.IsAny&lt;string&gt;())).Returns(httpClient);
              return httpClient;
          }
      }
  
      internal class HttpDelegatingHandlerStub : DelegatingHandler
      {
          private readonly Func&lt;HttpRequestMessage, CancellationToken, Task&lt;HttpResponseMessage&gt;&gt; _handlerFunc;
          public HttpDelegatingHandlerStub()
          {
              _handlerFunc = (request, cancellationToken) =&gt; Task.FromResult(request.CreateResponse(HttpStatusCode.OK));
          }
  
          public HttpDelegatingHandlerStub(Func&lt;HttpRequestMessage, CancellationToken, Task&lt;HttpResponseMessage&gt;&gt; handlerFunc)
          {
              _handlerFunc = handlerFunc;
          }
  
          protected override Task&lt;HttpResponseMessage&gt; SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
          {
              return _handlerFunc(request, cancellationToken);
          }
      }
  }
  </code></pre>
  <p>Output from the example:</p>
  <pre><code>content before: {
      &quot;test&quot;: &quot;true&quot;
  }
  content after: &quot;{\r\n    \&quot;test\&quot;: \&quot;true\&quot;\r\n}&quot;
  </code></pre>