Home > OS >  How to override default Content-type
How to override default Content-type

Time:10-23

I have a minimal-API ( Project Sdk="Microsoft.NET.Sdk.Web" ) app that has a GET endpoint that I would like to return an image/png.

The endpoint is:

app.MapGet("/text2img/{inputText}", (string inputText) => {
  var fileBytes = new ByteArrayContent(text2img(inputText).ToByteArray());
  var mimeType="image/png"; 
  var fileBytesArray = fileBytes.ReadAsByteArrayAsync().Result;
  return Results.File(new Microsoft.AspNetCore.Mvc.FileContentResult(fileBytesArray, mimeType).FileContents);
});

And it returns the correct bytes for a png-image, but the content-type is octet-stream:

HTTP/1.1 200 OK
Content-Length: 24975
Content-Type: application/octet-stream
Date: Fri, 22 Oct 2021 16:29:49 GMT
Server: Kestrel

How do I return the correct Content-type?

CodePudding user response:

Results.File (at least in the latest version) has parameter for contentType you can just pass byte array and content type to it:

app.MapGet("/img", () =>
{
    var mimeType = "image/png";
    var bytes = ...
    return Results.File(bytes, contentType: mimeType);
});
  • Related