Joydip Kanjilal
Contributor

How to measure API performance in ASP.NET Core

how-to
Nov 16, 20236 mins
APIsC#Development Libraries and Frameworks

Take advantage of MethodTimer.Fody to measure the execution speed of your APIs and keep your ASP.NET Core applications running smoothly.

shutterstock 1945585687 stopwatch with white markings on black background on digital screen
Credit: Speed Stock / Shutterstock

In today’s fast-paced digital landscape, let’s not kid ourselves about how fast we’re moving. Many of us, and the software we build, are still too slow. How do we know we’re even making progress?

To know for sure that things are improving, we first need to measure them. If you think the performance of your APIs is critical to the happiness of your users and the success of your application (and it is), you should regularly monitor this performance and ensure that any issues are reported early in the software development cycle.

An excellent tool for measuring API performance in .NET is MethodTimer.Fody. In this article we’ll examine how we can take advantage of MethodTimer.Fody to measure the performance of APIs in ASP.NET Core applications.

To use the code examples provided in this article, you should have Visual Studio 2022 installed in your system. If you don’t already have a copy, you can download Visual Studio 2022 here.

Create an ASP.NET Core Web API project in Visual Studio

First off, let’s create an ASP.NET Core 7 Web API project in Visual Studio 2022. Follow the steps outlined below.

  1. Launch the Visual Studio 2022 IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “ASP.NET Core Web API” from the list of templates displayed.
  4. Click Next.
  5. In the “Configure your new project” window, specify the name and location for the new project.
  6. Optionally check the “Place solution and project in the same directory” check box, depending on your preferences.
  7. Click Next.
  8. In the “Additional Information” window shown next, leave the “Use controllers (uncheck to use minimal APIs)” box checked. We won’t be using minimal APIs in this project.
  9. Elsewhere in the “Additional Information” window, leave the “Authentication Type” set to “None” (the default) and make sure the check boxes for “Enable Open API Support,” “Configure for HTTPS,” and “Enable Docker” remain unchecked. We won’t be using any of those features here.
  10. Click Create.

We’ll use this ASP.NET Core Web API project to measure API performance with MethodTimer.Fody in the sections below.

What is API performance and why is it important?

API performance is a term that refers to how quickly an API can process requests and return responses. This metric includes factors such as processing speed, computational efficiency, data retrieval, and the delivery of results to users. By analyzing these factors and deciphering the intricacies of API performance, you can make informed decisions when integrating APIs into your business applications.

Two key reasons to maintain good API performance are user experience and scalability. Fast and efficient API responses are necessary to delivering a smooth user experience. As the number of user requests to your application increases, the performance of the API becomes critical. If you have not designed your API to handle load efficiently, you risk degraded performance, increased response times, and even system failures.

Clearly, API performance can directly impact the competitiveness of your business.

Install the MethodTimer.Fody NuGet package

On to measuring API performance with MethodTimer.Fody. First add the MethodTimer.Fody NuGet package to the Web API project you just created. To do this, select the project in the Solution Explorer window and right-click and select “Manage NuGet Packages.” In the NuGet Package Manager window, search for the MethodTimer.Fody package and install it.

Alternatively, you can install the package via the NuGet Package Manager console by entering the line shown below.

PM> Install-Package MethodTimer.Fody

In addition to installing the MethodTimer.Fody package, you will need to add a configuration file named FodyWeavers.xml to your project. Create a new file named FodyWeavers.xml at the root directory of the project and enter the following code in the file.

<?xml version="1.0" encoding="utf-8"?>
<Weavers>
  <MethodTimer />
</Weavers>

Create API methods in ASP.NET Core

Next we’ll create some API methods in order to profile their performance. Create a new entity class named Author and replace the generated code with the following code.

public class Author
{
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
}

Now create a new API controller named AuthorController in a file having the same, name with a .cs extension. Replace the generated code with the following code.

using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
namespace IDG.MethodTimer.Fody.Demo.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AuthorController : ControllerBase
    {
        private readonly List<Author> authors = new List<Author>();
        public AuthorController()
        {
            authors.Add(new Author()
            {
                Id = 1,
                FirstName = "Joydip",
                LastName = "Kanjilal"
            });
            authors.Add(new Author()
            {
                Id = 2,
                FirstName = "Paul",
                LastName = "Smith"
            });
        }
        [HttpGet]
        public IEnumerable<Author> Get()
        {
            return authors;
        }
        [HttpGet("{id}", Name = "Get")]
        public Author Get(int id)
        {
            return authors.Find(x => x.Id == id);
        }
    }
}

Apply the [Time] attribute to your API methods

To measure the execution time of API methods with MethodTimer.Fody, we must apply the [Time] attribute to those methods. So apply the [Time] attribute to your action methods as shown in the code snippet given below.

[Time]
[HttpGet]
public IEnumerable<Author> Get()
{
    return authors;
}

[Time]
[HttpGet("{id}", Name = "Get")]
public Author Get(int id)
{
    return authors.Find(x => x.Id == id);
}

Measure the performance of your API methods

When you run the application and browse any of the two endpoints that have the [Time] attribute applied on them, you’ll able to see the execution time of the API methods as shown in Figure 1 below.

methodtimer 01 IDG

Figure 1: MethodTimer.Fody at work!

Note that the execution time shows zero milliseconds. That’s because our implementation of the controller is minimalistic, with just a couple of records being returned from the action method. If you’d like to see a difference, you can slow down your action method by using the Thread.Sleep method as shown in the code snippet given below.

[Time]
[HttpGet]
public IEnumerable<Author> Get()
{
    Thread.Sleep(1000);
    return authors;
}

When you run the application again and browse the same endpoint, the output should look similar to that in Figure 2.

methodtimer 02 IDG

Figure 2: The HttpGet action method shows the execution time.

While there are several tools available for profiling performance of applications, you should choose one based on your requirements. API developers should focus on optimizing database queries, implementing caching, optimizing code, and minimizing unnecessary data transfers. Naturally, you should also monitor performance regularly.

Joydip Kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author