Home > Blockchain >  How can I, using a WebApplication MapGet handler, send an image as an HTTP response?
How can I, using a WebApplication MapGet handler, send an image as an HTTP response?

Time:05-05

Here's my sample command line app. I'm using Windows 10 with dot-net 6.

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.IO;
var app = WebApplication.Builder();
app.MapGet("/", MyGet);
byte[] MyGet(HttpContext context)
{
   context.Response.ContentType="image/png";
   return File.ReadAllBytes("MyImage.png");
}
app.Run();

When I run this and browse to the server, instead of a PNG image returned, I get the bytes in JSON/Base64 form.

Using a string return type for MyGet happily sends plain text or HTML to the client. How can I send arbitrary bytes instead?

CodePudding user response:

If you want to send the image as file download:

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", MyGet);
void MyGet(HttpContext context)
{
   context.Response.ContentType="image/png";
   context.Response.Headers.Add("content-disposition", $"attachment; filename=test");
   context.Response.SendFileAsync(new FileInfo("MyImage.png").FullName);
}
app.Run();

CodePudding user response:

context.Response.Body.WriteAsync(someBytes);

(I am grateful to user rawel for pointing me in this direction. I had tried Response.Body.Write before posting my question but this didn't work, an error complaining that synchronous writes were not allowed. In my case, sending the response is the last thing my get function does, so there's no problem leaving the async operation open.)

  • Related