Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Community Proposals
Community Proposals
tag:snake search within a tag
answers:0 unanswered questions
user:xxxx search by author id
score:0.5 posts with 0.5+ score
"snake oil" exact phrase
votes:4 posts with 4+ votes
created:<1w created < 1 week ago
post_type:xxxx type of post
Search help
Notifications
Mark all as read See all your notifications »
Code Reviews

Welcome to Software Development on Codidact!

Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.

Measure ASP.NET Core 3.1 Web API action execution times

+2
−0

This is basically an unanswered code review request of mine from CodeReview Stack Exchange.

I want to be able to log as accurately as possible, the time spent by a certain Web API action in an ASP.NET Core 3.1 Web API.

I found out this very old question dealing with a similar issue in ASP.NET. The solution relies on global action filters, but in ASP.NET Core, I think middlewares are more appropriate.

From a client's perspective I want to measure as accurately as possible the following time:

Time to first byte - Time spent to send the request

So, using a slightly modified code from c-sharpcorner I have implemented the following:

/// <summary>
/// tries to measure request processing time
/// </summary>
public class ResponseTimeMiddleware
{
    // Name of the Response Header, Custom Headers starts with "X-"  
    private const string ResponseHeaderResponseTime = "X-Response-Time-ms";

    // Handle to the next Middleware in the pipeline  
    private readonly RequestDelegate _next;

    ///<inheritdoc/>
    public ResponseTimeMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    ///<inheritdoc/>
    public Task InvokeAsync(HttpContext context)
    {
        // skipping measurement of non-actual work like OPTIONS
        if (context.Request.Method == "OPTIONS")
            return _next(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[ResponseHeaderResponseTime] = responseTimeForCompleteRequest.ToString();

            var logger = context.RequestServices.GetService<ILoggingService>();
            string fullUrl = $"{context.Request.Scheme}://{context.Request.Host}{context.Request.Path}{context.Request.QueryString}";
            logger?.LogDebug($"[Performance] Request to {fullUrl} took {responseTimeForCompleteRequest} ms");

            return Task.CompletedTask;
        });

        // Call the next delegate/middleware in the pipeline   
        return _next(context);
    }
}

Startup.cs (plugging the middleware)

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory,
    ILoggingService logger, IHostApplicationLifetime lifetime, IServiceProvider serviceProvider)
{
    app.UseResponseCaching();

    app.UseMiddleware<ResponseTimeMiddleware>();

    // ...
}

Is this a good approach? I am mostly interested in optimizing the following:

  • time measurement accuracy
  • overhead
History
Why does this post require attention from curators or moderators?
You might want to add some details to your flag.
Why should this post be closed?

0 comment threads

0 answers

Sign up to answer this question »