Azure Application Insights for ASP.NET Core applications

Azure Application Insights for ASP.NET Core applications

With Application Insights, you can monitor your web application no matter where or how they run. If your application is running and has network connectivity to Azure, telemetry can be collected. In this post I will demonstrate how to configure configure Azure Application Insights for an ASP.NET Core.

Application Insights can collect the following telemetry from your ASP.NET Core application:

  • Requests
  • Dependencies
  • Exceptions
  • Performance counters
  • Heartbeats
  • Logs

Create an Application Insight resource

First you need to have a valid Application Insights connection string. This string is required to send any telemetry to Application Insights. If you need to create a new Application Insights resource to get a connection string, see Create an Application Insights resource.

Enable Application Insights server-side telemetry

  1. Install the Application Insights SDK NuGet package for ASP.NET Core The following code sample shows the changes to be added to your project's .csproj file.
  2. Using the .NET CLI execute the following command:
dotnet add package Microsoft.ApplicationInsights.AspNetCore --version 2.21.0

The following code will be added to your project's .csproj file.

<ItemGroup>
    <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.15.0" />
</ItemGroup>
  1. Add AddApplicationInsightsTelemetry() to your startup.cs Add builder.Services.AddApplicationInsightsTelemetry(); after the WebApplication.CreateBuilder() method in your Program class, as in this example:
var builder = WebApplication.CreateBuilder(args);

// Enables Application Insights telemetry collection.
builder.Services.AddApplicationInsightsTelemetry(APPLICATIONINSIGHTS_CONNECTION_STRING);

var app = builder.Build();
  1. Set up the connection string It is best practice that you specify the connection string in configuration. The following code shows how to specify the connection string in appsettings.json. Make sure appsettings.json exists in the application root folder.
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ApplicationInsights": {
    "ConnectionString": "Copy your connection string from Application Insights Resource Overview"
  }
}

Run your web application

Run your web application and make requests to it. Telemetry should now flow to Application Insights. The Application Insights SDK automatically collects incoming web requests to your application, along with the following telemetry. You should now be able to monitor, detect and diagnose exceptions and discover for e.g. how many users are effected. But also correlate failures with exceptions, dependency calls, and traces. Examine dumps, and trace logs.