博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
ActionFilterAttribute 全局记录API日志
阅读量:5833 次
发布时间:2019-06-18

本文共 3654 字,大约阅读时间需要 12 分钟。

1、API项目下创建MonitorApiAttribute

public class MonitorApiAttribute : ActionFilterAttribute    {        private static readonly string key = "enterTime";        public override void OnActionExecuted(HttpActionExecutedContext filterContext)        {            try            {                object beginTime = null;                if (filterContext.Request.Properties.TryGetValue(key, out beginTime))                {                    var user = HttpContext.Current.User as UserInfo;//登录时储存的User                    var indentify = user != null ? user.Id.ToString() : null;                                       MonitorApiHelper.Monitor(beginTime, filterContext.Request, filterContext.Response, indentify);                }            }            catch (Exception)            {            }            base.OnActionExecuted(filterContext);        }        public override void OnActionExecuting(HttpActionContext actionContext)        {            actionContext.Request.Properties[key] = DateTime.Now.ToBinary();            base.OnActionExecuting(actionContext);        }    }

 

2、Common项目下创建MonitorApiHelper帮助类

public class MonitorApiHelper    {               public static async void Monitor(object beginTime, HttpRequestMessage httpRequestMessage, HttpResponseMessage httpResponseMessage, string indentify = "", string moduleId = "")        {            DateTime time = DateTime.FromBinary(Convert.ToInt64(beginTime));            var responseTime = Convert.ToInt32((DateTime.Now - time).TotalMilliseconds);            var appId = "myapp";            var clientType = 0;            var responseStatus = 0;            var request = HttpContext.Current.Request;            var browerVersion = request.UserAgent;            var clientIP = request.UserHostAddress;            var serviceName = request.Url.AbsoluteUri;            var requestType = MethodConver(request.HttpMethod);            var inputParams = ReadStream(await httpRequestMessage.Content.ReadAsStreamAsync());            var outputParams = ReadStream(await httpResponseMessage.Content.ReadAsStreamAsync());            //在这里使用以上变量记录日志操作        }        private static int MethodConver(string method)        {            switch (method.ToUpper())            {                case "GET":                    return 0;                case "POST":                    return 1;                case "PUT":                    return 2;                case "DELETE":                    return 3;                default:                    break;            }            return 0;        }        public static string ReadStream(Stream stream)        {            var content = string.Empty;            if (stream != null)            {                stream.Seek(0, SeekOrigin.Begin);                int len = (int)stream.Length;                byte[] inputByts = new byte[len];                stream.Read(inputByts, 0, len);                stream.Position = 0;                content = Encoding.UTF8.GetString(inputByts);            }            return content;        }    }

 

3、WebApiConfig下增加代码  config.Filters.Add(new MonitorApiAttribute());

public static class WebApiConfig    {        public static void Register(HttpConfiguration config)        {            // Web API configuration and services            // Web API routes            config.MapHttpAttributeRoutes();            config.Filters.Add(new MonitorApiAttribute());            config.Routes.MapHttpRoute(                name: "DefaultApi",                routeTemplate: "api/{controller}/{id}",                defaults: new { id = RouteParameter.Optional }            );        }    }

 

转载于:https://www.cnblogs.com/lizhenhong/p/9591470.html

你可能感兴趣的文章
C++ primer plus
查看>>
python mysqlDB
查看>>
UVALive 3942 Remember the Word Tire+DP
查看>>
从微软的DBML文件中我们能学到什么(它告诉了我们什么是微软的重中之重)~目录...
查看>>
被需求搞的一塌糊涂,怎么办?
查看>>
c_数据结构_队的实现
查看>>
jquery 选择器总结
查看>>
Qt设置背景图片
查看>>
【阿里云文档】常用文档整理
查看>>
java中的Volatile关键字
查看>>
前端自定义图标
查看>>
实验二
查看>>
独立开发一个云(PaaS)的核心要素, Go, Go, Go!!!
查看>>
MyBatis使用DEMO及cache的使用心得
查看>>
网站文章如何能自动判定是抄袭?一种算法和实践架构剖析
查看>>
【OpenCV学习】滚动条
查看>>
ofo用科技引领行业进入4.0时代 用户粘性连续8个月远甩摩拜
查看>>
兰州青年志愿者“中西合璧”玩快闪 温暖旅客回家路
查看>>
计划10年建10万廉价屋 新西兰政府:比想象中难
查看>>
甘肃发首版《3D打印职业教育教材》:校企合作育专才
查看>>