简体   繁体   English

Web API响应时间

[英]Web API response time

I'm building a server monitoring system and want to send a request to a Web API and get the server's health in a JSON object if it's ok, if its database connections are working, its response time, etc. 我正在构建服务器监视系统,并希望将请求发送到Web API,并通过JSON对象(如果数据库连接正常,响应时间等)获取服务器的运行状况。

How can I implement the response time, saying how long the Web API takes to answer the request? 如何实现响应时间,说Web API回答请求需要多长时间?

If you want to implement Web Api Monitoring, you can create a custom DelegatingHandler to track action duration and status. 如果要实施Web Api监视,则可以创建自定义DelegatingHandler来跟踪操作持续时间和状态。

Here is a very basic example to measure operation duration. 这是一个测量操作持续时间的非常基本的示例。 The duration is added to response (quite useless) ; 持续时间被添加到响应中(相当无用); it's better to store this kind of data to a dedicated repository. 最好将这类数据存储到专用存储库中。

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;
    }
}

您可以在客户端启动一个秒表 ,并在返回篷房时将其停止

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM