当前位置:首页 > Windows程序 > 正文

stopWatch.Elapsed.TotalMilliseconds));}}}} 在接口的action方法上添加过

2024-03-31 Windows程序

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]

技术分享图片

或者将过滤器添加到配置中,这样将相当于在每个接口上添加了过滤器

技术分享图片

演示

发送请求:

技术分享图片

接口响应:

技术分享图片

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/33358.html

Jm-杰米博客Jamie
草根站长的技术交流乐园!IT不会不要紧快来好好学习吧!
  • 20786文章总数
  • 7494585访问次数
  • 建站天数
  • 友情链接