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

发布时间 2023-04-23 10:56:21作者: 风中起舞

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;

        private readonly string _operModul; // 操作模块
        private readonly string _operType; // 操作类型
        private readonly string _operDesc; // 操作说明

        public ActionFilter(string operModul, string operType, string operDesc)
        {
            _operModul = operModul;
            _operType = operType;
            _operDesc = operDesc;
        }

        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));

                //获取过滤器标记的参数
                var a = _operModul;
                var b = _operType;
                var c = _operDesc;

                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方法上添加过滤器

        [HttpPost]
        [ActionFilter("测试", "新增", "订单新增功能")]
        public IHttpActionResult Test([FromBody] string myString)
        {
            try
            {
                int a = 10, b = 0;
                int c = a / b;
                return Ok(new { code = 200, msg = "ok" });
            }
            catch (Exception ex)
            {
                return Ok(new { code = 500, msg = ex.Message, error = ex});
            }
            
        }