某一站點只負責提供視頻文件,因此本來只做爲一個靜態文件Web服務器,但如今一個需求是請求某個視頻文件時有多是播放文件,也有多是下載文件,可是不能添加太多程序,要儘量以最少的代碼實現功能。web
經過實現IHttpHandler
接口,過濾Url請求,根據是否攜帶參數區分行爲c#
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
中註冊該實現:app
<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>
這樣直接請求視頻時仍是播放視頻,請求時攜帶任何參數就會變成下載該視頻。ide