0

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", () =>
 {    
    
    
 });
    
4

1 回答 1

1

您可以使用该Results.Stream()方法从最小的 api 返回流。

string wwwroot = builder.Environment.WebRootPath;
...
app.MapGet("/video", () =>
{
    string filePath = Path.Combine(wwwroot, "test.mp4");
    return Results.Stream(new FileStream(filePath, FileMode.Open));
});

stream 参数在响应发送后被释放。

Results.Stream接受其他一些可能对您有用的可选参数,例如fileDownloadName, 和contentType(默认为)。"application/octet-stream"设置enableRangeProcessing: true为启用范围请求

如果您愿意,上述内容可以很容易地调整为将 afilename作为参数。您需要考虑验证(同样适用于当前代码 TBH)。经过测试并为我工作。

于 2022-02-09T01:21:11.103 回答