I was trying to achieve this following different tutorials but did not succeed. How do I handle a http range request in minimal API to serve video stream ?
I have this bare minimal setup code for API with a single GET path "/video" mapped. I also made a folder "wwwroot" inside project folder. I placed in there a mp4 video file named "test.mp4". Would it be possible for someone knowledgeable to write a simple example of how to stream this file inside my mapped route ?
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
builder.Logging.AddJsonConsole();
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.MapGet("/video", () =>
{
});
CodePudding user response:
You can use the Results.Stream()
method to return a stream from a minimal api.
string wwwroot = builder.Environment.WebRootPath;
...
app.MapGet("/video", () =>
{
string filePath = Path.Combine(wwwroot, "test.mp4");
return Results.Stream(new FileStream(filePath, FileMode.Open));
});
The stream parameter is disposed after the response is sent.
Results.Stream
takes a few other optional parameters such as fileDownloadName
, and contentType
(which defaults to "application/octet-stream"
) that might be useful to you. Set enableRangeProcessing: true
to enable range requests.
The above could easily be adapted to take a filename
as a parameter, if you wish. You would need to consider validation (applies equally to the current code TBH). Tested and working for me.