asp.net 简单记录请求的客户端和服务端 处理时间
最近项目需要简单记录一下 ajax客户端和服务端处理时间,服务端时间的思路是借用BeginRequest和EndRequest事件,为了不影响现有接口返回的数据格式,因此服务处理时间放在response 的header里面。
BeginRequest += (sender, args) => { HttpContext.Current.Items["ServerStartTime"] = DateTime.Now.Ticks.ToString(); }; EndRequest += (sender, args) => { long ticks = ConvertUtil.ToLong(HttpContext.Current.Items["ServerStartTime"], 0); TimeSpan ts = new TimeSpan(DateTime.Now.Ticks -ticks); HttpContext.Current.Response.Headers.Set("ServerProcessTime", Math.Ceiling(ts.TotalMilliseconds).ToString()); };
客户端在借助beforeSend和complete事件,实现code如下:
$(["get", "post"]).each(function (i, ajaxType) { G[ajaxType] = function (option) { $.ajax({ url: option.url, data: option.data, type: ajaxType, beforeSend: function () { option.StartClientTime = new Date(); }, dataType: "json", cache: option.cache, async: option.async, success: function (d) { alert(d) }, complete: function (XMLHttpRequest, textStatus) { var endClientTime = new Date(); try { var logRequest = false; if (option.url.indexOf("/Member/AAA") >= 0 || option.url.indexOf("/Member/BBB")>=0 || option.url.indexOf("/Member/CCC")>=0) { logRequest = true; } if (logRequest) { //记录请求时间 var costTime = endClientTime - (option.StartClientTime - 0); var serverTime = XMLHttpRequest.getResponseHeader("ServerProcessTime"); console.log("Rquest " + option.url + " totlal cost time:" + costTime + " Server time:" + serverTime); var logdata = { ajaxUrl: option.url, TotalTicks: costTime, ServerTicks: serverTime }; $.post("/xxx/LogRequest", logdata); } } catch (e) { } } }); }; });
最后在调用LogRequest把时间记录到日志系统中。
windows技术爱好者
标签:
Asp.net
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
2013-04-04 SSIS2012 发布 部署
2013-04-04 SSIS2005 包的部署、配置、定期执行
2013-04-04 SQL Server2012登录记录怎么删除?