Connect to Azure Application Insights from .NET C# Web Application hosted in Localhost or Azure Web App





5.00/5 (1 vote)
Connect .NET Web App to Azure Application Insights hosted in Localhost or Azure Web App using the same code. The approach is recommended by Microsoft and is applicable for .NET 6 and above.
Introduction
This tip demonstrates the simplest and shortest piece of code required to connect your .NET Web App to Application Insights, both from localhost and Azure Web App.
Using the Code
Right click on the following: Project >> Add >> Application Insights Telemetry
Microsoft.ApplicationInsights.AspNetCore
NuGet package will get added as Dependencies.
Update the package to the latest version if not added automatically.
Add the Application Insight Connection String to the appsettings.json file as follows:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ApplicationInsights": {
"ConnectionString": "Add App Insight Connection String Here"
}
}
Add the Application Insight Connection String to the Azure Web App Configuration as shown below. The key name should be the same.
P.S. Connection String is the recommended approach to connect to Application Insights instead of Instrumentation Key. Certain features are available in Application Insights only when connected through connection string.
Add the following code to Program.cs file:
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
//The following line enables Application Insights telemetry collection.
builder.Services.AddApplicationInsightsTelemetry();
// Add services to the container.
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days.
// You may want to change this for production scenarios,
// see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
}
}
How to Test the Above Approach?
- Create two Application Insight instances.
AppIns_1
andApp_Ins_2
. - Add the connection string for
AppIns_1
in appsettings.json. - Add the connection string for
AppIns_2
in Azure Web App. - Build and execute the application in localhost, browse a few pages.
- Deploy the application in Azure Web App and browse a few pages.
- The logs from localhost will be found in
AppIns_1
- The logs from Azure Web App will be found in
AppIns_2
- Please note that there is a slight delay in the logs getting reflected in App Insights.
History
- 14th July, 2023: Initial version