检测 .NET HttpHandler 中的字节范围请求
我有一个 HttpHandler ,它将对传入的请求进行一些检查,并在某些情况下执行某些功能。需要检查的条件之一是请求是否是字节范围请求。这是怎么做到的?
I have a HttpHandler which will do some checks on the incoming requests and in certain cases perform some function. One of the conditions that needs to be checked is whether the request is a byte-range request. How is this done?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要在
Request
对象中查找Range
标头,该对象是传递给ProcessRequest
方法的HttpContext
的一部分。HttpRequest
类中没有Range
属性,因此您必须查看Headers
。如果存在Range
,则其形式为:Range: bytes=-
其中
和
是整数。例如,如果有人想要从文件中间获取 64K:Range: bytes=32768-98304
您必须将文本解析为数字并进行相应处理。
You need to look for a
Range
header in theRequest
object that's part of theHttpContext
passed to yourProcessRequest
method. There is noRange
property in theHttpRequest
class, so you'll have to look in theHeaders
. If there is aRange
it will be of the form:Range: bytes=<start>-<end>
Where
<start>
and<end>
are integers. For example, if somebody wanted 64K from the middle of a file:Range: bytes=32768-98304
You'll have to parse the text into numbers and handle accordingly.
请注意,Range 标头语法还允许使用“0-500、100-1500”(多个范围)和“-500”(最后 500 个字节)等内容。请参阅 RFC 2616 了解详细信息,这些详细信息太长,无法在此处引用。
Note that the Range header syntax also allows for things like "0-500, 100-1500" (multiple ranges) and "-500" (last 500 bytes). See RFC 2616 for the gory details, which are too long to quote here.
基于@brent-keller 评论中链接到上面的博客文章,该评论又引用了 CodePlex 条目 ——我进行了以下修改。它已通过 FDM 进行测试(可在此处获取)。 (尚)不支持多范围请求。不需要
Web.config
条目。CodePlex 的原始方法包含一个错误 -
Accept-Ranges
标头的值应仅为bytes
,而不是要返回的字节范围。它属于Content-Range
标头。下载仍然有效,但如果您犯了这个错误,您将无法获得字节服务。为了简洁和可读性,此修改版本进行了重构。它还有一个优点,即返回的文件不一定与实际 URL 绑定 — 事实上,可以直接从浏览器调用处理程序,并在需要时使用查询字符串参数。这使得动态文件/数据创建和响应成为可能。
希望有人能用它做点好事。
HTTP 处理程序
范围请求
范围响应
Based on the blog post linked to above in the comment by @brent-keller—which in turn references a CodePlex entry—I came up with the edits below. It's tested with FDM (available here). MultiRange requests are not supported (yet). No
Web.config
entries are required.The original method at CodePlex contains an error—the
Accept-Ranges
header should have a value of simplybytes
, not the byte range to be returned. That belongs to theContent-Range
header. The download still works, but you won't get byte serving if you make that mistake.This modified version is refactored for brevity and readability. It also has the advantage that the file returned isn't necessarily tied to the actual URL—in fact the handler may be called directly from the browser and with query string arguments if need be. This enables dynamic file/data creation and response.
Hopefully someone can do some good with it.
HTTP Handler
Range Request
Range Response