c# - Web API 响应时间

标签 c# asp.net-web-api

我正在构建一个服务器监控系统,我想向 Web API 发送请求,并在 JSON 对象中获取服务器的健康状况、数据库连接是否正常、响应时间等。

如何实现响应时间,即 Web API 需要多长时间来响应请求?

最佳答案

如果您想实现 Web Api 监控,您可以创建一个自定义的 DelegatingHandler 来跟踪操作持续时间和状态。

这是衡量操作持续时间的一个非常基本的示例。将持续时间添加到响应中(非常无用);最好将此类数据存储到专用存储库中。

public class MonitoringDelegate : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
        CancellationToken cancellationToken)
    {
        var watcher = Stopwatch.StartNew();
        var response = await base.SendAsync(request, cancellationToken);
        watcher.Stop();

        //store duration somewheren here in the response header
        response.Headers.Add("X-Duration", watcher.ElapsedMilliseconds.ToString());

        return response;
    }
}

关于c# - Web API 响应时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23724844/

相关文章:

c# - 编辑其他用户的注册表项

javascript - LinkBut​​ton 单击事件未触发 asp.net

c# - CLR 在调用结构的方法时如何工作

asp.net - Azure Web App - 限制对 API 管理的访问

c# - WebAPI - 路由

c# - 如何在 .NET 中为我的应用程序创建配置文件

c# - 如何在c#中只显示小数点后2个空格

.net - ASP.NET Web API 自定义 ReasonPhrase 破坏自托管应用程序

rest - 在数据库中发现错误数据的 HTTP 响应状态代码

asp.net-mvc - MVC WebApi 在 C# 中获取传递对象