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();