简体   繁体   中英

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.

How can I implement the response time, saying how long the Web API takes to answer the request?

If you want to implement Web Api Monitoring, you can create a custom DelegatingHandler to track action duration and status.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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