Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Minimal API How to Return/Download Files from URL

I'm working on minimal api, what I'm trying is when the user visits /download it immediately downloads my picture named add.png.

But no matter what I try it doesn't work because I either get an empty page with only {}

Is this possible? if so how

This is my code that I've tried so far. (I got access denied with all permissions on the location!)

app.MapGet("/download", async () =>
  {
      var path = "add.png";
      using (var stream = new FileStream(path, FileMode.Open))
      {
          stream.CopyToAsync(stream);
      }
      var ext = Path.GetExtension(path).ToLowerInvariant();
      var result = (ext, Path.GetFileName(path));
      return result;
  });

How do I do this for when the user does /download within my api that he is going to download a file?

Thanks in advance

like image 731
Teun Avatar asked Dec 10 '25 12:12

Teun


1 Answers

You can use Results.File to return file to download from your Minimal APIs handler:

app.MapGet("/download", () =>
{
    var mimeType = "image/png";
    var path = @"path_to_png.png";
    return Results.File(path, contentType: mimeType);
});
like image 127
Guru Stron Avatar answered Dec 13 '25 12:12

Guru Stron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!