首页 > 编程语言 >asp.net 分片下载

asp.net 分片下载

时间:2023-10-14 13:34:11浏览次数:40  
标签:Core asp HTTP Content range video file 分片 net

参考:

https://learn.microsoft.com/en-us/answers/questions/726990/serving-video-file-stream-from-asp-net-core-6-mini

https://khalidabuhakmeh.com/partial-range-http-requests-with-aspnet-core

 

HTTP Range Requests and Partial Responses With ASP.NET Core

Long gone are the days when internet speed was a problem for most technology workers. Anecdotally, I downloaded a video for this post, misplaced it, and rather than search my local machine, I decided to download it again. It’s a perk of living in the future. While consumers of the internet may take bandwidth and data transfer for granted, developers might want to consider what repeated complete downloads will do to budget expenditure and user experience.

In this post, we’ll see three ways to process HTTP range requests, what benefits we’ll see from using them, and how they work in our web browser.

Let’s get started.

The Complete Download Problem

The internet’s evolution has brought us to a point where we commonly transmit gigabytes of information from a server to a client. Platforms like Netflix, HBO Max, and TikTok will stream video files as their core experience. While most consumers might watch a video from start to finish, interruptions do happen, having to pause or abandon a viewing session.

How do we resume a file from a particular point?

Well, there’s a solution for this problem directly in the HTTP specification. It’s called HTTP range requests.

What’s an HTTP Range Request?

**HTTP range requests allow a client to ask the server to send a portion of a response to the client. ** Partial HTTP range requests are most beneficial when used with large file downloads and have the added benefit of supporting pause and resume functionality on the client.

To initiate a partial range request, the client must initiate a request to the server and will potentially receive two headers: Accept-Ranges and Content-Length. If the server supports partial range requests, the value for Accept-Ranges will be bytes; otherwise, the value will be none. The Content-Length is the total file size the client can expect when retrieving the resource.

HTTP/1.1 200 OK
...
Accept-Ranges: bytes
Content-Length: 100000

In some cases, the server might support HEAD requests, allowing us to receive only the resource’s header information without transmitting the entire payload.

Assuming the server can handle partial range requests, we can now add a Range header to our HTTP request with the format of bytes=[start]-[end].

GET /puppies.mp4 HTTP/1.1
Host: localhost
Range: bytes=0-100

When successful, we’ll receive an HTTP status code of 206 Partial Content along with additional headers of Content-Range and Content-Length.

HTTP/1.1 206 Partial Content
Content-Range: bytes 0-100/100000
Content-Length: 100
...
(binary content)

It is important to note that Content-Length is the response payload’s length, not the total file size. To retrieve the entire file size, we can parse the Content-Range header and use the value after the /.

In general, we can expect three different status code responses from a server:

  • 206 Partial Content: The server successfully handled a partial request and sending a partial payload.
  • 416 Requested Range Not Satisfiable: Something is wrong with the partial request, likely out of bounds, and the response reflects a failure.
  • 200 OK: No support for partial requests and the server is returning the complete resource.

To read a more complete details about HTTP Range requests, I recommend reading the Mozilla documentation.

Great, so how do we use Partial request requests and responses with ASP.NET Core?

Static File Middleware and Partial Requests

The first and most straightforward way of using HTTP range requests is to let ASP.NET Core do all the work. The StaticFileMiddleware component of ASP.NET Core supports partial responses. Adding files into our wwwroot folder will automatically allow ASP.NET Core and the server to return larger media files in parts.

In our Startup class, we need to add the StaticFileMiddleware registration in our Configure method.

app.UseStaticFiles();
C#

Within our wwwroot folder, we’ll drop a video.mp4 file, which will allow the server to send the file to a client.

Finally, within a Razor pages files, we can add a video tag that will retrieve our video file and render it to the browser.

<div>
    <h2>Static</h2>
    <video
        src="video.mp4"
        width="400"
        controls>
    </video>
</div>
HTML

Let’s see what happens in our web browser developer tools.

using the Static File Middleware to return partial HTTP response to client

As we can see, we see a status code of 206 Partial Content, along with headers for Accept-Ranges and Content-Range. In this particular example, the byte range is small that the payload returned is the complete video.

ASP.NET Core MVC and Partial Requests

Sometimes we need to hide files behind a layer of business logic, and the StaticFileMiddleware might not be the right fit for our problem. Luckily for ASP.NET Core MVC developers, this functionality is exposed through the FileStreamResult type, which implements the IActionResult interface. The FileStreamResult type can take any stream and attempt to handle an HTTP range request.

In this example, we’ll use the same video file but create a readable stream to pass as a parameter to the Controller’s File method.

public class VideoController : Controller
{
    private readonly IWebHostEnvironment environment;

    public VideoController(IWebHostEnvironment environment)
    {
        this.environment = environment;
    }
    
    // GET
    [HttpGet, Route("videos/video.mp4")]
    public IActionResult Index()
    {
        var video = environment
            .WebRootFileProvider
            .GetFileInfo("video.mp4")
            .CreateReadStream();

        return File(video, "video/mp4", enableRangeProcessing: true);
    }
}
C#

We’ll also notice we need to set the optional parameter of enableRangeProcessing to true to get the expected functionality.

Let’s update the Razor page to call the controller action.

<div>
    <h2>Partial</h2>
    <video
        src="@Url.Action("Index", "Video")"
        width="400" controls>
    </video>
</div>
Razor C#

Let’s see what’s happening in our browser’s development tools.

using the FileStreamResult to return partial http response

Similar to the StaticFileMiddleware, we’ll see all the hallmarks of a range request and a partial response.

We have the added benefit of supporting all streams, not just streams reading from a local disk.

Conclusion

The HTTP range request happens transparently for most browser users, but knowing that partial responses are possible opens a world of new pause/resume features for developers building native clients. Luckily, we can continue to use ASP.NET Core as a proxy to large media files while getting the benefits of this particular HTTP specification feature.

If we need a different behavior from ASP.NET Core, we can access the header values directly from the HttpRequest class and create our responses according to our needs.

It is important to note that the underlying host server, IIS and Kestrel, must have support for this feature; otherwise, it won’t work.

I hope you enjoyed this blog post and let me know on Twitter, @buhakmeh, if you use this particular feature and how.

As always, thanks for reading.

 

 

 

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

Aedma Martin21Reputation points Feb 8, 2022, 8:15 PM

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   0 commentsNo comments  0{count} votes    
 Accepted answer
  1.   Zhi Lv - MSFT28,006 Reputation points• Microsoft Vendor Feb 9, 2022, 1:37 PM

    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

 

标签:Core,asp,HTTP,Content,range,video,file,分片,net
From: https://www.cnblogs.com/xinyublog/p/17764064.html

相关文章

  • Netty源码编译
    Netty源码编译想了解Netty源码,最好先从netty-example开始,多跑几个example,了解Netty的实际应用。编译netty-example会出现很多乱七八糟的问题,根本原因是因为缺少io.netty.util.collection包。解决方法1.先installDev-Tools模块2.接着installCommon模块instal......
  • 关于 Chrome 开发者工具 Network 面板里观察到的 net ERR_CERT_AUTHORITY_INVALID 错
    我在Chrome访问一个网站时,在Chrome开发者工具Network面板里观察到的netERR_CERT_AUTHORITY_INVALID错误:net::ERR_CERT_AUTHORITY_INVALID这种错误通常会在你试图访问的网站的SSL证书存在问题时出现。SSL(SecureSocketLayer)证书用于建立用户和网站服务器之间的安......
  • 基于Win 自带的.NET FrameWork平台,使用文本文件编写C#代码,命令行编译以及引用第三方库
    转载自https://www.infoq.cn/article/2015/12/visual-studio-windows 不用VisualStudio也能开发.NETWindows应用邵思华2015-12-29本文字数:2915字阅读完需:约10分钟对于.NET应用的开发人员而言,以VisualStudio(简称VS)作为首选的开发工具应当是一种最......
  • 根据实际工作经验总结一下个人.Net高并发处理做法
    场景描述1.用户下单,商品库存已经不足了,但还是扣减了2.医生开方,药品不足了,但还是被开了出去···类似场景解决思路思路1:预扣库存用户下单时,系统先进行预扣库存操作,然后后将“下单业务”发布到MQ(消息队列)进行处理,成功通知,失败回滚预扣库存操作对于预扣库存时可能出现的“......
  • 使用Hot Chocolate和.NET 6构建GraphQL应用 —— 创建Attribute中间件
    需求在部分接口添加一个机器人校验的功能思路读者们可以看下使用HotChocolate和.NET6构建GraphQL应用(5)——实现Query过滤功能,我们可以自定义创建一个类似的特性中间件来对接口进行管理.添加了该特性的接口即可实现机器人校验功能.实现输入对象///用户输入public......
  • sprintf、snprintf、vsprintf、asprintf、vasprintf函数
    1.sprintfexternintsprintf(char*__restrict__s,constchar*__restrict__format,...);2.snprintf/*MaximumcharsofoutputtowriteinMAXLEN.*/externintsnprintf(char*__restrict__s,size_t__maxlen,......
  • 基于.Net 的 AvaloniUI 多媒体播放器方案汇总
    基于.Net的AvaloniUI多媒体播放器方案汇总摘要随着国产化的推进,相信.Net的桌面端的小伙伴的可能已经有感受到了。为了让.Net的桌面框架能够跨桌面平台,首选的就是Avalona-UI。为了让AvaloniaUI能够跨多个平台播放视频,这里测试主要播放视频形式是使用RTSP。所以,在这篇博文中......
  • 深入探讨 C# 和 .NET 中 async/await 的历史、背后的设计决策和实现细节
    前言对`async/await`的支持已经存在了十多年。它的出现,改变了为.NET编写可伸缩代码的方式,你在不了解幕后的情况下也可以非常普遍地使用该功能。从如下所示的同步方法开始(此方法是“同步的”,因为在整个操作完成并将控制权返回给调用方之前,调用方将无法执行任何其他操作)://Syn......
  • .NET5_IIS安装与运行发布
    一、IIS安装1、打开控制面板、点击程序 2、点击启动或关闭Windows功能4、勾选InternetInformationServices下所有的选项全部划勾5、确定二、IIS运行与发布.netcore发布到IIS上出现HTTP错误500.19,错误代码:0x8007000d错误提示: 错误原因是缺少了模块,原因有两种:1......
  • 基于ZXing.NET实现的二维码生成和识别客户端
    一、前言ZXing.Net的一个可移植软件包,是一个开源的、多格式的1D/2D条形码图像处理库,最初是用Java实现的。已经过大量优化和改进,它已经被手动移植。它与.Net2.0、.Net3.5、.Net4.x、.Net5.x、.Net6.x、.Net7.x、WindowsRT类库和组件、UWP、.NetStandard1.x和2.0x、.NetC......