MVC 过滤器使用 ActionFilterAttribute
在asp.net mvc 中 webapi 和 mvc 处理消息是两个不同的管道,Asp.net mvc 和 webapi 为我们提供的 ActionFilterAttribute 拦截器,通过 重写 OnActionExecuting,来 拦截action的请求消息,当执行OnActionExecuting完成以后才真正进入请求的action中,action运行完后又把控制权给了 OnActionExecuted,这个管道机制可以使我们用它来轻松实现 权限认证、日志记录 ,跨域以及很多需要对全局或者部分请求做手脚的的功能。
大概的流程如下
通过ActionFilterAttribute ,就能拦截action 处理的所有内容,包括请求提交的参数以及返回值。由于asp.net MVC 与webapi 是两个完全独立的管道:
- MVC由System.Web.Mvc.ActionFilterAttribute 来做action请求的拦截。
- webapi 由 System.Web.Http.Filters.ActionFilterAttribute 来处理。
因此拦截action请求是完全不相干的两个通道,于此同时,当我们需要注册全局的ActionFilterAttribute 这两个也是分开注册的:
MVC 直接在System.Web.Mvc.GlobalFilterCollection 这个全局管道里面注册 ActionFilter ,位置在App_Start目录>FilterConfig 类>RegisterGlobalFilters 方法 使用参数filters , filters.Add(new YourMvcAttribute()) 添加你的mvc ActionFilterAttribute 。
web API 在System.Web.Http.Filters 中注册, 在项目的App_Start 目录>WebApiConfig类中>Register 方法中加入使用 config参数, config.Filters.Add(new YourWebApiAttribute()); 添加你的 webapi ActionFilterAttribute
这样就可以注册你的 ActionFilterAttribute 成为全局的Filter,系统中请求经过Action 之前或之后 都会被你的ActionFilter 拦下来做处理然后在转交下去。
好了道理已经讲完了,现在开始我自己要实现的 日志记录功能,
需求是记录所有访问webapi action的(请求地址、内容、访问用户、提交的参数、返回的结果、以及一些客户端的信息)
由于MVC 框架 提倡契约编程,在你自定义的Attribute 时,需要遵守契约规范, 【YourFilterName】+Attribute ,所以我的filter名字为 LogAttribute
一、定义过滤器
/// <summary>/// 全局日志过滤器(在WebApiConfig中注册),每个action执行都会执行该过滤器/// </summary>public class LogAttribute : ActionFilterAttribute{public override void OnActionExecuting(HttpActionContext filterContext){if (!SkipLogging(filterContext)){//获取action名称string actionName = filterContext.ActionDescriptor.ActionName;//获取Controller 名称string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;//获取触发当前方法的Action方法的所有参数 var paramss = filterContext.ActionArguments;string Content = Newtonsoft.Json.JsonConvert.SerializeObject(paramss);LogHelper.GetInstance(" LogFilter").Write(string.Format("OnActionExecuting、控制器:{0},动作:{1},参数:{2}", controllerName, actionName, Content));}base.OnActionExecuting(filterContext);}public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext){if (!SkipLogging(actionExecutedContext.ActionContext)){//获取action名称string actionName = actionExecutedContext.ActionContext.ActionDescriptor.ActionName;//获取Controller 名称string controllerName = actionExecutedContext.ActionContext.ActionDescriptor.ControllerDescriptor.ControllerName;//获取触发当前方法的Action方法的所有参数 var paramss = actionExecutedContext.ActionContext.ActionArguments;string Content = Newtonsoft.Json.JsonConvert.SerializeObject(paramss);LogHelper.GetInstance(" LogFilter").Write(string.Format("OnActionExecuted、控制器:{0},动作:{1},参数:{2}", controllerName, actionName, Content));}base.OnActionExecuted(actionExecutedContext);}/// <summary>/// 判断控制器和Action是否要进行拦截(通过判断是否有NoLogAttribute过滤器来验证)/// </summary>/// <param name="actionContext"></param>/// <returns></returns>private static bool SkipLogging(HttpActionContext actionContext){return actionContext.ActionDescriptor.GetCustomAttributes<NoLogAttribute>().Any() || actionContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes<NoLogAttribute>().Any();}}/// <summary>/// 不需要日志记录的过滤器/// </summary>[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true)]public class NoLogAttribute : Attribute{}
二、在WebApiConfig.cs中注册全局过滤器
public static class WebApiConfig{public static void Register(HttpConfiguration config){config.Filters.Add(new LogAttribute());config.Routes.MapHttpRoute(name: "DefaultApi",routeTemplate: "api/{controller}/{action}/{id}",defaults: new { id = RouteParameter.Optional });}}
三、在控制器中使用
// GET api/sodetails/5public string Get(int id){return "{\"Value\":\"" + id + "\"}";}[NoLog]public string Post([FromBody]string value) //该action不添加日志信息{return "{\"Value\":\"" + value + "\"}";}
四、日志效果
2018/5/14 14:11:11636619038710767426
L_Message : OnActionExecuting、控制器:SoDetails,动作:Get,参数:{"id":123}
L_Level : INFO
L_Folder : LogFilter
L_CreatTime : 2018-05-14 14:11:11.075
L_ServerHostName : sh-ysl-bi-hzq
L_ServerHostIP : 10.10.40.5
---------------------------------------
2018/5/14 14:11:14636619038740781337
L_Message : OnActionExecuted、控制器:SoDetails,动作:Get,参数:{"id":123}
L_Level : INFO
L_Folder : LogFilter
L_CreatTime : 2018-05-14 14:11:14.078
L_ServerHostName : sh-ysl-bi-hzq
L_ServerHostIP : 10.10.40.5
---------------------------------------
MVC 过滤器使用 ActionFilterAttribute相关推荐
- ASP .NET Core MVC 过滤器之一 ActionFilterAttribute
.NET Core MVC 登陆或权限过滤器 using Microsoft.AspNetCore.Mvc.Filters; using System.Linq; using Finance.Web. ...
- ASP.NET MVC过滤器(一)
MVC过滤器是加在 Controller 或 Action 上的一种 Attribute,通过过滤器,MVC 网站在处理用户请求时,可以处理一些附加的操作,如:用户权限验证.系统日志.异常处理.缓存等 ...
- Mvc过滤器的使用【转载】
前言 在开发大项目的时候总会有相关的AOP面向切面编程的组件,而MVC(特指:Asp.Net MVC,以下皆同)项目中不想让MVC开发人员去关心和写类似身份验证,日志,异常,行为截取等这部分重复的代码 ...
- MVC过滤器详解和示例
MVC过滤器一共分为四个:ActionFilter(方法过滤器),ResultFilter(结果过滤器,感觉不是很好听,就这样叫吧),AuthorizationFilter(授权过滤器),Except ...
- MVC过滤器-AOP思想初探
AOP:面向切面编程."给程序统一添加新功能的一种思想". 它是对传统OOP编程的一种补充. OOP关注需求功能模块,封装良好的类,并让他们有属于自己的行为,侧重业务逻辑的实现. ...
- ASP .NET MVC过滤器
MVC过滤器一共分为四个: ActionFilter:方法过滤器 ResultFilter:结果过滤器 AuthorizationFilter:授权过滤器 ExceptionFilter:异常处理过滤 ...
- ASP.NET MVC 过滤器(一)
ASP.NET MVC 过滤器(一) 前言 前面的篇幅中,了解到了控制器的生成的过程以及在生成的过程中的各种注入点,按照常理来说篇幅应该到了讲解控制器内部的执行过程以及模型绑定.验证这些知识了.但是呢 ...
- asp.net MVC 过滤器使用案例:统一处理异常顺道精简代码
asp.net MVC 过滤器使用案例:统一处理异常顺道精简代码 参考文章: (1)asp.net MVC 过滤器使用案例:统一处理异常顺道精简代码 (2)https://www.cnblogs.co ...
- ASP.NET MVC 过滤器(三)
ASP.NET MVC 过滤器(三) 前言 本篇解说行为过滤器的运行过程,过滤器实现.使用方式有AOP的意思.能够通过学习了解过滤器在框架中的运行过程从而获得一些AOP方面的知识(在顺序运行的过程中, ...
最新文章
- WinCE CEDDK之Bus操作函数
- C++ Primer 5th笔记(9)chapter9 顺序容器 string
- 5.16GW光伏扶贫,各省费用如何筹措?
- 3DSlicer17:Logics
- C++总结笔记(十一)—— Lambda表达式的应用
- .NET Core 中如何调试 死锁 ?
- java util logging_简单日志记录,使用java.util.logging
- 工作总结9:vue处理token
- java各种的不好_译文《最常见的10种Java异常问题》
- TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
- 苹果iPhone XI奋起直追?直接升级四摄镜头
- 如何免费注册使用虚拟主机和二级域名建站
- django中collectstatic的使用
- java 7 update 79下载_java 7下载|java运行环境(JDK 7 Update 67)官方版下载 - 3322软件站
- cpu性能参数如何看?
- 文件无法复制到c盘的解决办法
- 华为主题包hwt下载_hwtTool-hwtTool(华为主题开发工具)下载 v9.1.3.302官方版--pc6下载站...
- Ubuntu 安装 H3C iNode 客户端
- 如何优雅的给你的APK文件打上签名
- 万能遥控程序c语言,51单片机万能红外遥控解码程序