Search code examples
c#asp.netasp.net-coreasp.net-web-apiminimal-apis

ASP.NET Core Results.File vs Results.Stream


I am returning a file from my ASP.NET Core API using this code:

app.MapGroup("file").MapGet("/export", async () => 
{
    var fileStream = someCode1();
    var fileType= someCode2();
    var fileName= someCode3();

    return Results.File(
        fileStream,
        fileType.ToMimeType(),
        fileName.Full);
}
  • fileStream is an open stream to a file on the disk
  • the 2nd parameter is the file's mime type as string
  • the 3rd parameter is the file's name

I noticed that I can also use Results.Stream() instead and the file download still works normally. Does anyone know what the difference is between those two methods and when should they be used?

Results.File: https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.http.results.file?view=aspnetcore-8.0

Results.Stream: https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.http.results.stream?view=aspnetcore-8.0


Solution

  • These two methods are explicitly documented as being aliases for each other. For example, the docs for Results.File states that:

    This API is an alias for Stream(Stream, String, String, Nullable, EntityTagHeaderValue, Boolean).

    If you dig into the source, you'll also see that both Results.File and Results.Stream end up returning an instance of the same FileStreamHttpResult class.