How the get the real download time (not request time) in .NET core web api

61 Views Asked by At

We have a .NET core WEB-API which have an endpoint that provide a file. The endpoint is called from NB-IoT devices (very low bandwidth). The download takes up to 2 miuntes (for 90KB).

We want to track how long the download takes on the server. But if I add a middleware for tracking, I only get the request time (some milli seconds), not the time how long data is transmitted to the client through a TCP connection.

We tried a lot of logging, but I was not able to get the real download time.

1

There are 1 best solutions below

1
On

You need to log the time at the server-side when the download starts and ends.

You need a middleware to handle it.

MiddleWare:

public class DownloadTimeMiddleware
{
    private readonly RequestDelegate _next;

    public DownloadTimeMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        var watch = new Stopwatch();
        watch.Start();

        context.Response.OnStarting(() =>
        {
            watch.Stop();
            var downloadTime = watch.Elapsed;

            // Log the download time here
            context.Response.Headers.Add("X-Download-Time", downloadTime.TotalMilliseconds.ToString());
            Console.WriteLine($"Download time: {downloadTime}");

            return Task.CompletedTask;
        });

        await _next(context);
    }
}

Add Middleware to the Startup:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseMiddleware<DownloadTimeMiddleware>();
}

This middleware will track the duration of all requests


Front End side You can use this code:

var xhr = new XMLHttpRequest();
xhr.open('GET', 'Your Download URL', true);

xhr.onreadystatechange = function() {
  if (xhr.readyState === XMLHttpRequest.DONE) {
    if (xhr.status === 200) {
      var downloadTime = xhr.getResponseHeader('X-Download-Time');
      console.log('Download time: ' + downloadTime + 'ms');
    }
  }
};

xhr.send();