打赏

netframework webapi IogAttribute记录request参数和错误信息

参考博客

https://www.cnblogs.com/hnsongbiao/p/7039666.html

书写LogFilterAttribute

 public class LogFilterAttribute : ActionFilterAttribute
    {
        private CommonService _commonService;
        public LogFilterAttribute()
        {
            _commonService = new CommonService();
        }
        /// <summary>
        /// Action执行后
        /// </summary>
        /// <param name="actionExecutedContext"></param>
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            if (actionExecutedContext.Exception != null)
            {
                var url = actionExecutedContext.ActionContext.Request.RequestUri;
                var param = actionExecutedContext.ActionContext.ActionArguments;
                var paramJson= Newtonsoft.Json.JsonConvert.SerializeObject(param);
                var error = $"Exception:{DateTime.Now}(ㄒoㄒ){url}(ㄒoㄒ){paramJson}(ㄒoㄒ){actionExecutedContext.Exception.Message}";
                _commonService.SaveLog(error);
            }
        }
    }

在webapi.Config中注册LogFilterAttribute

 public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            // Configure Web API to use only bearer token authentication.
            config.SuppressDefaultHostAuthentication();
            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
            config.Filters.Add(new LogFilterAttribute());

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
            config.Routes.MapHttpRoute(
                name: "SwaggerIndex",
                routeTemplate: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = RouteParameter.Optional }
            );
            var json = config.Formatters.JsonFormatter;
            json.SerializerSettings.PreserveReferencesHandling =
                Newtonsoft.Json.PreserveReferencesHandling.Objects;
            config.Formatters.Remove(config.Formatters.XmlFormatter);
        }

 

posted @ 2019-06-20 13:52  KiteRunner1988  阅读(206)  评论(0编辑  收藏  举报