How to use MiniProfiler in ASP.Net Core

Take advantage of the simple and powerful MiniProfiler to identify performance bottlenecks in your ASP.Net Core MVC applications

How to use MiniProfiler in ASP.Net Core MVC applications
Thinkstock

Performance of web applications is a serious concern the world over. Developers have many tools they can use to profile web applications and find the performance bottlenecks. MiniProfiler is one such tool — a simple yet powerful tool for profiling web applications. MiniProfiler helps you detect slow running queries, slow server response times, and more. 

MiniProfiler is available for .Net, ASP.Net, and ASP.Net Core. You’ll find the documentation for MiniProfiler on GitHub. This article presents a discussion of MiniProfiler, why it is useful, and how we can use it to profile ASP.Net Core MVC applications and discover performance issues in our applications.

Create an ASP.Net Core MVC project in Visual Studio 2017

First off, let’s create an ASP.Net Core MVC project in Visual Studio. If Visual Studio 2017 is up and running in your system, follow the steps given below to create an ASP.Net Core MVC project.

  1. Launch the Visual Studio 2017 IDE.
  2. Click on File > New > Project.
  3. Select “ASP.Net Core Web Application (.Net Core)” from the list of templates displayed.
  4. Specify a name for the project.
  5. Click OK to save the project.
  6. A new window, “New .Net Core Web Application…”, will be displayed.
  7. Select .Net Core as the runtime and ASP.Net Core 2.1 (or later) from the drop-down list at the top. I’m using .Net Core 2.2.
  8. Select “Web Application (Model-View-Controller)” as the project template (as shown in Figure 1 below).
  9. Ensure that the check boxes “Enable Docker Support” and “Configure for HTTPS” are unchecked. We won’t be using these features here.
  10. Ensure that “No Authentication” is selected. We won’t be using authentication here either.
  11. Click OK. 

Following these steps will create a new ASP.Net Core MVC project in Visual Studio. We’ll use this project to profile the application using MiniProfiler.

miniprofiler 1 IDG

Figure 1: Creating a new ASP.Net Core MVC project in Visual Studio 2017. 

Install and configure MiniProfiler in ASP.Net Core

To get started working with MiniProfiler, you need to install the necessary NuGet package. To install MiniProfiler in your project, follow the steps given below.

  1. Select the project in the Solution Explorer window. 
  2. Right-click and select “Manage NuGet Packages...”
  3. Search for the “MiniProfiler.AspNetCore.Mvc” package. 
  4. Click “Install” to install the NuGet package. 

This will install the MiniProfiler.AspNetCore.Mvc NuGet package in your project. To start using MiniProfiler in your project, you will need to configure it in the Startup class. The following code snippet shows how you can call the AddMiniProfiler method on the IServiceCollection instance to add MiniProfiler to the pipeline.

public void ConfigureServices(IServiceCollection services)
        {
            services.AddMiniProfiler(options =>
            options.RouteBasePath = "/profiler"
            );
            //Usual code
        }

You can learn more about the options you can specify when registering MiniProfiler with the pipeline from the MiniProfiler website here.

You should also invoke the UseMiniProfiler method on the IApplicationBuilder instance to start using MiniProfiler in your controllers and views.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
       app.UseMiniProfiler();
       //Usual code
    }

Next add the following two lines inside the <html> tag in the _Layout.cshtml file.

@using StackExchange.Profiling
@addTagHelper *, MiniProfiler.AspNetCore.Mvc

You should also specify where in the web page the MiniProfiler window should be displayed, i.e., the render position. To do this, you can include the following statement inside the <body> tag.

<mini-profiler position="@RenderPosition.Right" max-traces="5" />

Use steps in MiniProfiler to profile ASP.Net Core MVC code

MiniProfiler will let you know the page load times and information related to performance of the database queries. When you run the application, the output will appear as in Figure 2 below. Note the MiniProfiler window at the top right corner of the screen.

miniprofiler 2 IDG

Figure 2: MiniProfiler in action. 

To learn the time taken for a specific portion of your code to execute, you can take advantage of steps. The following code snippet illustrates how this can be achieved.

public IActionResult Index()
 {
       var miniProfiler = MiniProfiler.Current;
       List<Author> authors = new List<Author>();
       miniProfiler.RenderIncludes(this.HttpContext);
       using (miniProfiler.Step("Get Authors"))
       {
           authors.Add(new Author() { Id = 1, FirstName = "Joydip", LastName = "Kanjilal", Address = "Hyderabad, India" });
           authors.Add(new Author() { Id = 2, FirstName = "Stephen", LastName = "Smith", Address = "NY, USA" });
           authors.Add(new Author() { Id = 3, FirstName = "Anand", LastName = "Narayanan", Address = "Chennai, India" });
           authors.Add(new Author() { Id = 4, FirstName = "Steve", LastName = "Jones", Address = "London, UK" });
       }
           return View(authors);
 }

The following code snippet shows what the abovementioned Author class looks like.

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

When you run the application, you’ll observe the time taken by the step we defined as shown in Figure 3 below. The entry I’ve highlighted in green shows the time taken to execute the “Get Authors” step.

miniprofiler 3 IDG

Figure 3: Time taken to execute a step in MiniProfiler. 

If you want to ignore a specific portion of your application’s code from profiling, you can specify the code to be ignored as shown in the code snippet below.

using (MiniProfiler.Current.Ignore())
{
  // Write code here that you don't
  // want MiniProfiler to profile
}

Use MiniProfiler to profile ADO.Net queries

You can also use MiniProfiler to profile ADO.Net queries. To do that you would need to take advantage of ProfileDbConnection and ProfileDbCommand as shown in the code snippet below.

using (SqlConnection connection = new SqlConnection(@"Data Source=JOYDIP\SQLEXPRESS; Initial Catalog=SyncDB; Trusted_Connection=Yes"))
     {
       using (ProfiledDbConnection profiledDbConnection = new ProfiledDbConnection(connection, MiniProfiler.Current))
         {
           if (profiledDbConnection.State != System.Data.ConnectionState.Open)
               profiledDbConnection.Open();
             using (SqlCommand command = new SqlCommand
              ("Select * From Authors", connection))
               {
                 using (ProfiledDbCommand profiledDbCommand =
                   new ProfiledDbCommand(command, connection,
                     MiniProfiler.Current))
                       {                               
                         var data =
                          profiledDbCommand.ExecuteReader();
              //Write code here to populate the list of Authors
                        }
                 }
          }                      
    }

Note how ProfileDbConnection and ProfileDbCommand wrap the DbConnection and DbCommand objects. You can learn more about how to profile source code using MiniProfiler from the MiniProfiler website.

MiniProfiler is a simple profiler for .Net, Ruby, Go, and Node.js. You can use MiniProfiler to profile queries that are generated by Dapper, Linq2SQL, and Entity Framework. In addition to being easy to use, MiniProfiler doesn’t add much overhead to your applications. You can use MiniProfiler to profile applications in production without significant performance impact. 

Copyright © 2019 IDG Communications, Inc.