Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Hosted-services / Azure

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

5.00/5 (1 vote)
14 Jul 2023CPOL1 min read 10K  
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.
This tip demonstrates the simplest and shortest piece of code required to connect you .NET Web App to Application Insights hosted in localhost or Azure Web App.

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:

JSON
{
  "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.

Image 1

Add the following code to Program.cs file:

C#
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?

  1. Create two Application Insight instances. AppIns_1 and App_Ins_2.
  2. Add the connection string for AppIns_1 in appsettings.json.
  3. Add the connection string for AppIns_2 in Azure Web App.
  4. Build and execute the application in localhost, browse a few pages.
  5. Deploy the application in Azure Web App and browse a few pages.
  6. The logs from localhost will be found in AppIns_1
  7. The logs from Azure Web App will be found in AppIns_2
  8. Please note that there is a slight delay in the logs getting reflected in App Insights.

History

  • 14th July, 2023: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)