c# - 如何获取 .NET WebAPI 调用的运行时间

标签 c# datetime logging asp.net-web-api

如何在 C# 中获取 .NET WebAPI 调用的运行时间?

我的日志文件需要这样的信息

我可以很容易地在 API 调用之前和之后执行 DateTime.Now(),但是,如果已经有一些东西...让我们使用它吧!

最佳答案

你可以使用过滤器

using System;
using System.Diagnostics;
using System.Net.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using System.Web.Mvc;

namespace App.Utility
{
    /// <summary>
    /// Used to log requests to server
    /// </summary>
    [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
    public class LogActionRequestsAttribute : ActionFilterAttribute
    {
        public LogActionRequestsAttribute()
        {
             //You can inject to constructors ILog or what ever
        }

        public static Stopwatch GetTimer(HttpRequestMessage request)
        {
            const string key = "__timer__";
            if (request.Properties.ContainsKey(key))
            {
                return (Stopwatch)request.Properties[key];
            }

            var result = new Stopwatch();
            request.Properties[key] = result;
            return result;
        }
        
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            
            var timer = GetTimer(actionContext.Request);
            timer.Start();
            base.OnActionExecuting(actionContext);
        }


        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            base.OnActionExecuted(actionExecutedContext);
            var timer = GetTimer(actionExecutedContext.Request);
            timer.Stop();
            var totalTime = timer.ElapsedMilliseconds;            
        }
    }
}

然后在webapi配置中

config.Filters.Add(
                (LogActionRequestsAttribute)
                    GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof (LogActionRequestsAttribute)));

AttributeUsage 防止调用属性两次。 但我认为其他选择可能是编写 http 模块以使用开始、结束请求事件,这可能是最好和精确的测量,在我的应用程序中它足以使用属性,因为几毫秒对我​​来说没什么大不了的

关于c# - 如何获取 .NET WebAPI 调用的运行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35501422/

相关文章:

python - 环境变量

.net - 使用 Enterprise Library 登录到滚动 CSV 文件

java - 如何删除 Java 记录器

c# - 使自定义类可用于 LINQ 查询

c# - 在 stringbuilder 中搜索字符串并替换整行 C#

c# - ReactiveExtensions Observable FromAsync 调用两次函数

python - 使用 strptime 将字符串转换为带有时区偏移的 python 日期类型对象

javascript - 如何将 moment js 日期时间转换为字符串,反之亦然

c# - 如何异步加载和显示图像

php - 将 DateInterval 格式化为 ISO8601