title: ASP.NET Core API Controller: Response.Body.WriteAsync base64 string not working
body: <p>I'm trying to return a base64 string representing a jpeg image from an API Controller and set it as the src of an <code>&lt;img&gt;</code> but all my attempts failed.</p>
  <p>Here is the very simple HTML:</p>
  <pre><code>&lt;img src=&quot;/api/TestBase64Image&quot; alt=&quot;image test&quot; /&gt;
  </code></pre>
  <p>And my controller:</p>
  <pre><code>[Route(&quot;api/[controller]&quot;)]
  public class TestBase64ImageController : Controller
  {
      private const string _base64Image = &quot;data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEBLAEsAAD/7Sfg.....&quot;;
      private const string _base64Image2 = &quot;/9j/4AAQSkZJRgABAQEBLAEsAAD/7Sfg.....&quot;;
  
      [HttpGet]
      public async Task Get()
      {
          Response.ContentType = &quot;image/jpeg&quot;;
          //Response.ContentType = &quot;text/plain&quot;;
          //Response.ContentType = new MediaTypeHeaderValue(&quot;image/jpeg&quot;).ToString();
          //Response.ContentType = new MediaTypeHeaderValue(&quot;text/plain&quot;).ToString();
  
          //Response.Headers.Add(&quot;Content-Length&quot;, _base64Image.Length.ToString());
          //HttpContext.Response.ContentLength = _base64Image.Length;
  
          await Response.Body.WriteAsync(Encoding.UTF8.GetBytes(_base64Image), 0, _base64Image.Length);
          //await Response.Body.FlushAsync();
      }
  }
  </code></pre>
  <p>I've tried several things, like removing <code>FlushAsync()</code>, changing the way to define the <code>ContentType</code>, include <code>data:image/jpeg;base64</code>, in the string or not but nothing is working.</p>
  <p>I've seen <a href="https://github.com/aspnet/Home/issues/822" rel="nofollow noreferrer">here</a> and <a href="https://stackoverflow.com/a/33186680/1203116">here</a> that writing in the Response body stream is doable, so I presume I'm on the good way (I've tried to return a simple string before but not working as well).</p>
  <p>Yes my base64 string is correct because I've also tried to include it directly into the HTML and the image shows up correctly.</p>
  <p>I precise I don't want to use any JavaScript or Razor view to achieve that, only pure HTML and my controller.</p>
  <p>Also please pay attention that I'm inside an API Controller. I can't do the same as we see in the <code>Configure</code> method in the <code>Startup</code> class of an empty ASP.NET Core project like:</p>
  <pre><code>app.Run(async (context) =&gt;
  {
      await context.Response.WriteAsync(&quot;Hello World!&quot;);
  });
  </code></pre>
  <p>Even though both Responses' types are <code>HttpResponse</code>, the one in my controller doesn't have any <code>Response.WriteAsync</code> but <code>Response.Body.WriteAsync</code></p>
  <p>Thanks for your help, it's been hours I'm searching but there is almost no resources about this yet for ASP.NET Core</p>