Click here to Skip to main content
15,887,267 members
Articles / Hosted Services / Azure
Tip/Trick

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

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
14 Jul 2023CPOL1 min read 8.7K   3  
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)


Written By
Technical Lead
India India
I'm a Software Architect proficient in .NET Core, Azure PaaS, Azure DevOps, and Microservices. With expertise in these technologies, I design scalable and secure software systems. My strong knowledge of .NET Core allows me to create high-performance applications with code reusability. I leverage Azure PaaS services like Azure App Service, Functions, and Storage to develop cloud-native solutions. Using Azure DevOps, I automate the software development lifecycle and establish efficient collaboration. Additionally, I specialize in Microservices architecture, ensuring applications are divided into independent services for flexibility and scalability. Overall, I architect cutting-edge software solutions optimized for the cloud environment.

Comments and Discussions

 
-- There are no messages in this forum --