首先继承自FilterAttribute类同时实现IActionFilter接口,代码如下:

//// <summary>
/// 防盗链Filter.
/// </summary>
public class AntiOutSiteLinkAttribute : ActionFilterAttribute, IActionFilter
{
public AntiOutSiteLinkAttribute(FileType fileType)
{
this.FileType = fileType;
} //// <summary>
/// 请求的文件类型.(文件或图片)
/// </summary>
public FileType FileType { get; set; } #region IActionFilter 成员 void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
{
HttpContextBase httpContext = filterContext.HttpContext;
if (null != httpContext.Request.UrlReferrer)
{
string serverDomain = httpContext.Request.Url.Host;
string refDomain = httpContext.Request.UrlReferrer.Host;
if (GetRootDomain(refDomain).Equals(GetRootDomain(serverDomain), StringComparison.OrdinalIgnoreCase))
{
return;//如果根域名相同就返回
}
} ContentResult cr = new ContentResult();
if (FileType == FileType.Image)
{
cr.ContentType = "image/jpeg";
FileInfo fi = new FileInfo(httpContext.Server.MapPath("~/Content/images/outsitelink.jpg"));
if (fi.Exists)
{
httpContext.Response.WriteFile(fi.FullName);
}
else
{
Bitmap bmp = new Bitmap(, );
Graphics g = Graphics.FromImage(bmp);
g.FillRectangle(Brushes.White, , , , );
g.DrawString("请不要盗链", new Font("Arial", ), Brushes.Red, new PointF(, ));
bmp.Save(httpContext.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);
}
}
else
{
cr.ContentType = "text/html";
cr.Content = string.Format("请不要盗链。返回<a href='{0}'>{1}</a>", Utils.AbsoluteWebRoot, BlogSettings.Instance.Name);
}
//将当前的上下文的ActionResult设置为我们的cr(ContentResult)
filterContext.Result = cr;
}
#endregion //// <summary>
/// 获取网站的根域名
/// </summary>
/// <param name="domain">网站的域名,不带"Http://"</param>
/// <returns></returns>
private string GetRootDomain(string domain)
{
if (string.IsNullOrEmpty(domain))
{
throw new ArgumentNullException("参数'domain'不能为空");
}
string[] arr = domain.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
if (arr.Length <= )
{
return domain;
}
else
{
return arr[arr.Length - ] + "." + arr[arr.Length - ];
}
}
} public enum FileType
{
File = ,
Image
}

然后我们建立一个用于处理文件请求的Controller,并应用上我们刚才建立的Filter:

public class FilesController : BaseController
{
[AntiOutSiteLink(FileType.Image)]
public ActionResult Image(string file)
{
return Content("Image From 4mvc");
} [AntiOutSiteLink(FileType.File)]
public ActionResult File(string file)
{
return Content("File From 4mvc");
}
}

测试结果:

对于ActionFilter的应用是很广泛的,需要灵活运用。对于其他应用,可以参考ASP.NET MVC Action Filter - 缓存与压缩 这一篇文章。

最新文章

  1. 餐饮连锁公司IT信息化解决方案一
  2. 我所记录的git命令(非常实用)
  3. Windows下安装Nginx反向代理服务器
  4. 解决oracle 端口 1521 本机127可通 其他ip不通
  5. Json 入门例子 多行数组 【1】
  6. Python 迭代删除重复项,集合删除重复项
  7. Symfony2学习笔记之HTTP Cache
  8. windows环境下安装 zookeeper
  9. scala-spark练手--dataframe数据可视化初稿
  10. SGU 200.Cracking RSA(高斯消元)
  11. Android中Context具体解释 ---- 你所不知道的Context
  12. 当chm文档点击左侧,右侧无内容时的解决方案
  13. nodejs 复制、移动文件
  14. CentOS7 更换yum源
  15. phpcms2008常用函数小结
  16. 理解ES6——Promise
  17. SuperSocket 最基础入门
  18. 学习用Node.js和Elasticsearch构建搜索引擎(5):mac本机部署canal
  19. Android SpannableString实现TextView的点击事件
  20. ionic3 使用html2canvas将数据导出为图片,并下载本地

热门文章

  1. CentOS下yum命令详解
  2. Maxim and Array CodeForces - 721D (贪心)
  3. IntelliJ IDEA调试方法补充
  4. 使用maven命令把jar包加入maven仓库
  5. element中使用button会刷新一遍页面
  6. MySQL主从同步最佳实践
  7. InnoDB存储引擎介绍-(6) 一. Innodb Antelope 和Barracuda区别
  8. redis初认知(持续更新中)
  9. 使用深度学习检测TOR流量——本质上是在利用报文的时序信息、传输速率建模
  10. Linux pwn入门教程——CTF比赛