How to use MiniProfiler in ASP.NET Core

By FoxLearn 1/7/2025 7:29:36 AM   13
Web application performance is a global concern, and developers have various tools to identify performance issues.

MiniProfiler is a simple yet powerful profiling tool that helps detect issues such as slow-running queries and server response times. It is available for .Net, ASP.Net, and ASP.Net Core.

To start using MiniProfiler in your project, install the MiniProfiler.AspNetCore.Mvc NuGet package by right-clicking the project in Solution Explorer, selecting Manage NuGet Packages, searching for the package, and clicking Install.

Add MiniProfiler to the Service Collection

After installation, configure MiniProfiler in the Startup.cs file by calling the AddMiniProfiler method in the ConfigureServices section to add it to the pipeline.

public void ConfigureServices(IServiceCollection services)
{
    services.AddMiniProfiler(options =>
    {
        options.RouteBasePath = "/profiler";
    });
    
    // Other service configurations
}

Enable MiniProfiler in the Application Pipeline

In the Configure method, invoke UseMiniProfiler on the IApplicationBuilder instance.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseMiniProfiler();
    
    // Other middleware configurations
}

Adding MiniProfiler to the _Layout.cshtml File

To integrate MiniProfiler into your ASP.NET Core MVC project, add the following lines inside the <head> tag of your _Layout.cshtml file:

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

Next, specify where on the web page you want the MiniProfiler window to appear by using the following code to define its render position:

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

Using MiniProfiler to Profile ASP.NET Core

MiniProfiler helps you measure page load times and provides performance data for database queries.

public IActionResult Index()
{
    var miniProfiler = MiniProfiler.Current;
    List<Product> products = new List<Product>();
    miniProfiler.RenderIncludes(this.HttpContext);

    using (miniProfiler.Step("Fetch Products"))
    {
        products.Add(new Product() { Id = 1, Name = "Laptop", Price = 1000 });
        products.Add(new Product() { Id = 2, Name = "Smartphone", Price = 500 });
        products.Add(new Product() { Id = 3, Name = "Tablet", Price = 300 });
    }

    return View(products);
}

Product class

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

When you run the application, MiniProfiler will display the time taken for the "Fetch Products" step in the profiler window.

If you'd like to exclude certain code from being profiled, wrap the code block with the Ignore method:

using (MiniProfiler.Current.Ignore())
{
    // Code that should not be profiled
}

Profiling ADO.NET Queries with MiniProfiler

MiniProfiler can also be used to profile ADO.NET queries.

To profile database interactions, wrap the SqlConnection and SqlCommand objects with ProfiledDbConnection and ProfiledDbCommand as shown below:

using (SqlConnection connection = new SqlConnection(@"Data Source=MYDATABASE; Initial Catalog=StoreDB; Trusted_Connection=True"))
{
    using (ProfiledDbConnection profiledDbConnection = new ProfiledDbConnection(connection, MiniProfiler.Current))
    {
        if (profiledDbConnection.State != System.Data.ConnectionState.Open)
            profiledDbConnection.Open();

        using (SqlCommand command = new SqlCommand("SELECT * FROM Products", connection))
        {
            using (ProfiledDbCommand profiledDbCommand = new ProfiledDbCommand(command, connection, MiniProfiler.Current))
            {
                var reader = profiledDbCommand.ExecuteReader();
                // Process the results
            }
        }
    }
}

MiniProfiler is a lightweight and efficient profiling tool for .NET applications that supports profiling ADO.NET queries and other data access frameworks like Dapper and Entity Framework. It adds minimal overhead to your application, making it suitable for use in both development and production environments.