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?
You need to look for a Range
header in the Request
object that's part of the HttpContext
passed to your ProcessRequest
method. There is no Range
property in the HttpRequest
class, so you'll have to look in the Headers
. If there is a Range
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.
-
Good answer. For the sake of future generations, a little sample code would be nice. Once I implement it, I hope you don't mind if I inject it into your answer. – Larsenal Dec 2 '10 at 1:42
-
@Larsenal: I didn't supply sample code because I don't have any. I remember working with this some years ago, but the code is long gone. Hopefully my short description is enough to get you started. I don't mind if you inject code into my answer. – Jim Mischel Dec 2 '10 at 14:50
-
FWIW, this lead to me to find the following post with code showing how to handle the ranged request: blogs.visigo.com/chriscoulson/… – Brent Keller Aug 14 '13 at 16:26
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.
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 simply bytes
, not the byte range to be returned. That belongs to the Content-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
Public Class Upload
Implements IHttpHandler
Public Sub ProcessRequest(Context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim oFile As FileInfo
oFile = New FileInfo(Context.Server.MapPath("~/0HCJ0LE.zip"))
Me.UploadRange(Context, oFile)
End Sub
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
Private Sub UploadRange(Context As HttpContext, File As FileInfo)
Dim oResponse As Response
Dim oRequest As Request
Dim _
nOffset,
nLength As Long
Using oReader As New StreamReader(File.FullName)
Context.Response.AddHeader("Accept-Ranges", "bytes")
oResponse = New Response(oReader)
oRequest = New Request(oResponse, Context)
If oRequest.HasRange Then
If oRequest.IsMultiRange Then
' At the moment we only support single ranges.'
' * Multiple range support requires some more work'
' * to comply with the specifications: http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html#sec19.2'
' *'
' * Multirange content must be sent with multipart/byteranges mediatype,'
' * (mediatype = mimetype)'
' * as well as a boundary header to indicate the various chunks of data.'
' '
' (?) Shoud this be issued here, or should the first'
' range be used? Or should the header be ignored and'
' we output the whole content?'
Me.ThrowBadRange(Context, oResponse)
Else
If oRequest.IsBadRange Then
Me.ThrowBadRange(Context, oResponse)
Else
Context.Response.StatusCode = 206
oResponse.Start = oRequest.Start
oResponse.End = oRequest.End
nOffset = oReader.BaseStream.Seek(oResponse.Start, SeekOrigin.Begin)
nLength = oResponse.End - oResponse.Start + 1
End If
End If
Else
nOffset = 0
nLength = oResponse.Size
End If
End Using
Context.Response.ContentType = MediaTypeNames.Application.Zip
Context.Response.AddHeader("Content-Disposition", $"attachment; filename={File.Name}")
Context.Response.AddHeader("Content-Length", nLength)
Context.Response.AddHeader(oResponse.HeaderName, oResponse.HeaderValue)
Context.Response.WriteFile(File.FullName, nOffset, nLength)
Context.Response.End()
End Sub
Private Sub ThrowBadRange(Context As HttpContext, Response As Response)
Context.Response.AddHeader(Response.HeaderName, Response.HeaderValue)
Throw New HttpException(416, "Requested range not satisfiable")
End Sub
End Class
Range Request
Friend NotInheritable Class Request
Public Sub New(Response As Response, Context As HttpContext)
Me.Response = Response
Me.Context = Context
End Sub
Public ReadOnly Property Start As Long
Get
If Me.Range(0) = String.Empty Then
Start = Me.Response.Size - Me.Range(1)
Else
Start = Me.Range(0)
End If
End Get
End Property
Public ReadOnly Property [End] As Long
Get
If Me.Range(0) = String.Empty Then
[End] = Me.Response.End
Else
If Long.TryParse(Me.Range(1), 0) Then
[End] = Me.Range(1)
Else
[End] = Me.Response.Size
End If
End If
[End] = Math.Min(Me.Response.End, [End])
End Get
End Property
Public ReadOnly Property HasRange As Boolean
Get
Return String.IsNullOrEmpty(Me.Context.Request.ServerVariables(HTTP_RANGE)) = False
End Get
End Property
Public ReadOnly Property IsMultiRange As Boolean
Get
Return Me.Context.Request.ServerVariables(HTTP_RANGE).Contains(",")
End Get
End Property
Public ReadOnly Property IsBadRange As Boolean
Get
Return Me.Start > Me.End OrElse Me.Start > Me.Response.Size - 1 OrElse Me.End >= Me.Response.Size
End Get
End Property
Private ReadOnly Property Range As List(Of String)
Get
Return Me.Context.Request.ServerVariables(HTTP_RANGE).Split("=")(1).Split("-").ToList
End Get
End Property
Private ReadOnly Response As Response
Private ReadOnly Context As HttpContext
Private Const HTTP_RANGE As String = "HTTP_RANGE"
End Class
Range Response
Friend NotInheritable Class Response
Public Sub New(Reader As StreamReader)
_Size = Reader.BaseStream.Length
Me.End = Me.Size - 1
End Sub
Public Property Start As Long
Public Property [End] As Long
Public ReadOnly Property Size As Long
Public ReadOnly Property HeaderName As String
Get
Return "Content-Range"
End Get
End Property
Public ReadOnly Property HeaderValue() As String
Get
Return $"bytes {Me.Start}-{Me.End}/{Me.Size}"
End Get
End Property
End Class