filter的介绍
filter在Web API中经常会用到,主要用于记录日志,安全验证,全局错误处理等;Web API提供两种过滤器的基本类型:actionfilterattribute,exceptionfilterattribute;两个类都是抽象类,actionfilter主要实现执行请求方法体之前(覆盖基类方法OnActionExecuting),和之后的事件处理(覆盖基类方法OnActionExecuted);exceptionfilter主要实现触发异常方法(覆盖基类方法OnException)。下面对前者类型做示例。
新建ActionFilter类
打印参数、返回值、以及接口响应时间:
public class ActionFilter : ActionFilterAttribute { private const string Key = "action"; private bool _IsDebugLog = true; public override void OnActionExecuting(HttpActionContext actionContext) { if (_IsDebugLog) { Stopwatch stopWatch = new Stopwatch(); actionContext.Request.Properties[Key] = stopWatch; string actionName = actionContext.ActionDescriptor.ActionName; Debug.Print(Newtonsoft.Json.JsonConvert.SerializeObject(actionContext.ActionArguments)); stopWatch.Start(); } } public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) { if (_IsDebugLog) { Stopwatch stopWatch = actionExecutedContext.Request.Properties[Key] as Stopwatch; if (stopWatch != null) { stopWatch.Stop(); string actionName = actionExecutedContext.ActionContext.ActionDescriptor.ActionName; string controllerName = actionExecutedContext.ActionContext.ActionDescriptor.ControllerDescriptor.ControllerName; Debug.Print(actionExecutedContext.Response.Content.ReadAsStringAsync().Result); Debug.Print(string.Format(@"[{0}/{1} 用时 {2}ms]", controllerName, actionName, stopWatch.Elapsed.TotalMilliseconds)); } } } }
在接口的action方法上添加过滤器
[ActionFilter]
或者将过滤器添加到配置中,这样将相当于在每个接口上添加了过滤器
演示
发送请求:
接口响应:
本博客Android APP 下载 |
![]() |
支持我们就给我们点打赏 |
![]() |
支付宝打赏 支付宝扫一扫二维码 |
![]() |
微信打赏 微信扫一扫二维码 |
![]() |
如果想下次快速找到我,记得点下面的关注哦!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!