ASP.NET Core API Controller: response line Response.Body.WriteAsync base64 not working

I am trying to return a base64 string representing a jpeg image from an API controller and set it as src <img>, but all my attempts failed.

Here is a very simple HTML:

<img src="/api/TestBase64Image" alt="image test" />

And my controller:

[Route("api/[controller]")]
public class TestBase64ImageController : Controller
{
    private const string _base64Image = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEBLAEsAAD/7Sfg.....";
    private const string _base64Image2 = "/9j/4AAQSkZJRgABAQEBLAEsAAD/7Sfg.....

    [HttpGet]
    public async Task Get()
    {
        Response.ContentType = "image/jpeg";
        //Response.ContentType = "text/plain";
        //Response.ContentType = new MediaTypeHeaderValue("image/jpeg").ToString();
        //Response.ContentType = new MediaTypeHeaderValue("text/plain").ToString();

        //Response.Headers.Add("Content-Length", _base64Image.Length.ToString());
        //HttpContext.Response.ContentLength = _base64Image.Length;

        await Response.Body.WriteAsync(Encoding.UTF8.GetBytes(_base64Image), 0, _base64Image.Length);
        //await Response.Body.FlushAsync();
    }
}

I tried several things, for example, deleting FlushAsync(), changing the definition method ContentType, include data:image/jpeg;base64, in the line or not, but nothing works.

I have seen here and here that the stream is executable in the response body, so I assume that I am on a good path (I tried to return a simple string earlier, but did not work either).

, base64 , HTML, .

JavaScript Razor , HTML .

, API. , Configure Startup ASP.NET Core, :

app.Run(async (context) =>
{
    await context.Response.WriteAsync("Hello World!");
});

, HttpResponse, Response.WriteAsync, Response.Body.WriteAsync

, , , ASP.NET Core .

+4
1

- base64, - UTF-8, .

, :

byte[] image = Convert.FromBase64String(_base64Image2);
await Response.Body.WriteAsync(image, 0, image.Length);

( , base64, URI .)

+3

Source: https://habr.com/ru/post/1657481/


All Articles