簡體   English   中英

如何計算 .net core Webapi 請求次數;

[英]How to count .net core Webapi request times;

我正在使用 ASP.NET 核心,我想計算/測量 Web API 請求響應時間。 我怎樣才能做到這一點?

謝謝。

您可以使用AppMetrics軟件包,該軟件包可幫助您記錄應用程序度量標准,例如請求率,計算一段時間內的用戶登錄數,測量執行數據庫查詢所花費的時間,測量可用內存量。

另外,您可以可視化輸出並在Grafana中顯示它們。

您可以創建自定義響應標頭,並使用中間件在此處放置經過的時間。

 public class ResponseTimeMiddleware
{
    // Name of the Response Header, Custom Headers starts with "X-"  
    private const string RESPONSE_HEADER_RESPONSE_TIME = "X-Response-Time-ms";
    // Handle to the next Middleware in the pipeline  
    private readonly RequestDelegate _next;
    public ResponseTimeMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public Task InvokeAsync(HttpContext context)
    {
        // Start the Timer using Stopwatch  
        var watch = new Stopwatch();
        watch.Start();
        context.Response.OnStarting(() => {
            // Stop the timer information and calculate the time   
            watch.Stop();
            var responseTimeForCompleteRequest = watch.ElapsedMilliseconds;
            // Add the Response time information in the Response headers.   
            context.Response.Headers[RESPONSE_HEADER_RESPONSE_TIME] = responseTimeForCompleteRequest.ToString();
            return Task.CompletedTask;
        });
        // Call the next delegate/middleware in the pipeline   
        return this._next(context);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM