场景
某一站点只负责提供视频文件,所以原本只作为一个静态文件Web服务器,但现在一个需求是请求某个视频文件时有可能是播放文件,也有可能是下载文件,但是不能添加太多程序,要尽可能以最少的代码实现功能。
方案
通过实现IHttpHandler
接口,过滤Url请求,根据是否携带参数区分行为
实现
VideoHandler.cs
:
using System;
using System.IO;
using System.Web;
namespace Video
{
public class VideoHandler : IHttpHandler
{
private static readonly object ReadFlag = new object();
public void ProcessRequest(HttpContext context)
{
var filePath = context.Server.MapPath(context.Request.Path);
byte[] bytes;
string videoType;
lock (ReadFlag)
{
//以字符流的形式下载文件
var fs = new FileStream(filePath, FileMode.Open);
bytes = new byte[(int) fs.Length];
videoType = fs.Name.Substring(fs.Name.LastIndexOf(@".", StringComparison.Ordinal) + 1,
fs.Name.Length - fs.Name.LastIndexOf(@".", StringComparison.Ordinal) - 1);
fs.Read(bytes, 0, bytes.Length);
fs.Close();
}
if (context.Request.QueryString.ToString() != String.Empty)
{
context.Response.ContentType = "application/octet-stream";
}
else
{
context.Response.ContentType = "video/" + videoType;
}
context.Response.BinaryWrite(bytes);
context.Response.Flush();
context.Response.End();
}
public bool IsReusable
{
get { return false; }
}
}
}
还要在Web.config
中注册该实现:
<system.web>
<compilation debug="true" targetFramework="4.0"/>
<httpHandlers>
<add verb="*" path="*.mp4" type="Video.VideoHandler,Video"/>
<add verb="*" path="*.webm" type="Video.VideoHandler,Video"/>
<add verb="*" path="*.ogv" type="Video.VideoHandler,Video"/>
</httpHandlers>
</system.web>
这样直接请求视频时还是播放视频,请求时携带任何参数就会变成下载该视频。