【C#】WebApi 添加过滤器,实现对请求参数和响应内容的日志记录

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]

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

演示

发送请求:

接口响应:

 

转载于:https://www.cnblogs.com/mychris/p/5157655.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值