1: public class StaticFileMiddleware
2: {
3: private async Task SendResponseAsync(PreconditionState state, HttpContext context, EntityTagHeaderValue etag, DateTimeOffset lastModified, string contentType, IFileInfo fileInfo)
4: {
5: switch (state)
6: {
7: //304 Not Modified
8: case PreconditionState.NotModified:
9: {
10: context.SetResponseHeaders(304, etag, lastModified, contentType, fileInfo.Length);
11: break;
12: }
13: //416 Precondition Failded
14: case PreconditionState.PreconditionFailed:
15: {
16: context.SetResponseHeaders(412, etag, lastModified, contentType,fileInfo.Length);
17: break;
18: }
19: case PreconditionState.Unspecified:
20: case PreconditionState.ShouldProcess:
21: {
22: //200 OK
23: if (context.UseMethods("HEAD"))
24: {
25: context.SetResponseHeaders(200, etag, lastModified, contentType, fileInfo.Length);
26: return;
27: }
28:
29: IEnumerable<RangeItemHeaderValue> ranges;
30: if (context.IsRangeRequest() && this.TryGetRanges(context, lastModified, etag, fileInfo.Length, out ranges))
31: {
32: RangeItemHeaderValue range = ranges.FirstOrDefault();
33: //416
34: if (null == range)
35: {
36: context.SetResponseHeaders(416, etag, lastModified,
37: contentType, fileInfo.Length);
38: return;
39: }
40: else
41: {
42: //206 Partial Content
43: context.SetResponseHeaders(206, etag, lastModified, contentType, fileInfo.Length, range);
44: context.Response.GetTypedHeaders().ContentRange = new ContentRangeHeaderValue(range.From.Value, range.To.Value, fileInfo.Length);
45: using (Stream stream = fileInfo.CreateReadStream())
46: {
47: stream.Seek(range.From.Value, SeekOrigin.Begin);
48: await StreamCopyOperation.CopyToAsync(stream, context.Response.Body, range.To - range.From + 1, context.RequestAborted);
49: }
50: return;
51: }
52: }
53: //200 OK
54: context.SetResponseHeaders(200, etag, lastModified, contentType, fileInfo.Length);
55: using (Stream stream = fileInfo.CreateReadStream())
56: {
57: await StreamCopyOperation.CopyToAsync(stream, context.Response.Body, fileInfo.Length, context.RequestAborted);
58: }
59: break;
60: }
61: }
62: }
63: }