实现请求同一视频时识别播放或下载行为

场景

某一站点只负责提供视频文件,所以原本只作为一个静态文件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>

这样直接请求视频时还是播放视频,请求时携带任何参数就会变成下载该视频。

转载于:https://www.cnblogs.com/clockwork/p/6368132.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值