Serving video file / stream from ASP Net Core 6 Minimal API

Aedma Martin 21 Reputation points
2022-02-08T12:15:47.907+00:00

Hi, I'm coming from NodeJs background and trying to get into building API's with ASP Net Core. I am experimenting with .Net Core 6 Minimal API as it looks quite familiar and simple to get going. I'm working on a project for streaming videos and I'm currently stuck on trying to figure out how do I serve / stream a video file for frontend?

I was trying different tutortials in

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


});

app.Run();
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,208 questions
0 comments No comments
{count} votes

Accepted answer
  1. Zhi Lv - MSFT 32,021 Reputation points Microsoft Vendor
    2022-02-09T05:37:58.727+00:00

    Hi @Aedma Martin ,

    In the Asp.net core Minimal API application, you can use the Results.File to return file to download from your minimal APIs handler, like this:

    app.MapGet("/video", (int id) =>  
    {  
        var filename = "file_example.mp4";  
        //Build the File Path.  
        string path = Path.Combine(_hostenvironment.WebRootPath, "files/") + filename;  // the video file is in the wwwroot/files folder  
      
        var filestream = System.IO.File.OpenRead(path);  
        return Results.File(filestream, contentType: "video/mp4", fileDownloadName: filename, enableRangeProcessing: true);   
    });  
    

    Then, in the main view page, use the video tag to display the video:

      <video autoplay controls src="https://localhost:7093/video?id=1"></video>  
    

    The result is like this:

    172471-image.png


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion

    4 people found this answer helpful.

0 additional answers

Sort by: Most helpful