ASP.NET Core Application Insights Step by step Implementation and Top 10 Questions and Answers
 Last Update: April 01, 2025      17 mins read      Difficulty-Level: beginner

Understanding ASP.NET Core Application Insights

ASP.NET Core Application Insights is a feature-rich diagnostic and monitoring tool designed by Microsoft to help developers gain insights into the performance and health of their web applications. This tool is seamlessly integrated with the ASP.NET Core framework and provides comprehensive monitoring capabilities, real-time diagnostics, analytics, and logging. In this article, we'll explore the details and significance of using Application Insights in ASP.NET Core applications.

1. What is Application Insights?

Application Insights is a fully managed Application Performance Management (APM) service that monitors your live web applications. It helps you diagnose and fix issues proactively, and improve the performance of your applications. It captures detailed telemetry data from your applications and presents it in a user-friendly dashboard, enabling developers to make informed decisions.

2. Key Features of Application Insights

  • Telemetry Collection: Application Insights automatically collects telemetry data about how users interact with your application, including page views, requests, and exceptions.
  • Performance Monitoring: It provides metrics related to application performance, such as response time, request counts, and failed requests.
  • Error Logging: Application Insights aggregates and categorizes application errors, providing actionable insights into issues.
  • Analytics and Visualization: It provides powerful analytics and visualization tools that allow developers to analyze telemetry data and identify trends.
  • User Flow Analysis: Application Insights tracks user flows across web pages and identifies areas where users might drop off or encounter issues.
  • Real-Time Monitoring: It provides real-time monitoring capabilities, allowing developers to detect anomalies and diagnose issues quickly.
  • Availability Tests: It can perform web tests to check the availability and response time of your application continuously.
  • Custom Telemetry: Developers can write custom code to collect additional telemetry data.

3. Setting Up Application Insights in ASP.NET Core

Setting up Application Insights in an ASP.NET Core application is straightforward and typically involves a few simple steps:

  1. Create an Application Insights Resource:

    • In the Azure portal, create a new Application Insights resource.
    • Once created, you'll receive an Instrumentation Key that is crucial for connecting your application to the Application Insights service.
  2. Install the Application Insights SDK:

    • Add the Microsoft.ApplicationInsights.AspNetCore NuGet package to your project.
  3. Configure Application Insights:

    • In the Program.cs file, add the following code to configure Application Insights with the Instrumentation Key:
      var builder = WebApplication.CreateBuilder(args);
      
      // Add services to the container.
      builder.Services.AddRazorPages();
      builder.Services.AddApplicationInsightsTelemetry(builder.Configuration["InstrumentationKey"]);
      
      var app = builder.Build();
      
      // Configure the HTTP request pipeline.
      if (!app.Environment.IsDevelopment())
      {
          app.UseExceptionHandler("/Error");
          app.UseHsts();
      }
      
      app.UseHttpsRedirection();
      app.UseStaticFiles();
      
      app.UseRouting();
      
      app.UseAuthorization();
      
      app.MapRazorPages();
      
      app.Run();
      
  4. Optional Configuration:

    • You can further customize the behavior of Application Insights by using the Startup.cs file to configure custom telemetry modules, initializers, and processors.

4. Using Application Insights

Once Application Insights is set up, you can start leveraging its features to gain insights into your application:

  • Dashboard Overview: The Overview dashboard provides a high-level summary of your application's health, including performance metrics, top issues, and user flows.
  • Performance Metrics: The Performance Metrics page displays detailed metrics about your application's performance, such as request counts, failed requests, and response times.
  • Failures: The Failures page tracks and categorizes application errors, providing actionable insights into issues.
  • Analytics: The Analytics blade provides a powerful query language called Kusto that allows you to query and analyze raw telemetry data.
  • Availability: The Availability page displays the results of web tests, showing the availability and response time of your application over time.

5. Customizing Telemetry

Application Insights allows you to customize the telemetry data collected by writing custom code. Here are a few ways to customize telemetry:

  • Custom Metrics: You can log custom metrics by using the TelemetryClient class.
  • Custom Events: You can log custom events by using the TelemetryClient class.
  • Custom Properties: You can add custom properties to existing telemetry data by using the ITelemetryInitializer interface.

6. Best Practices for Using Application Insights

  • Enable Application Insights Early: Enable Application Insights as soon as possible in the development cycle to track the performance of the application throughout its lifecycle.
  • Monitor Continuously: Continuously monitor your application to detect and diagnose issues proactively.
  • Use Analytics: Leverage the powerful analytics capabilities of Application Insights to gain deeper insights into your application's performance.
  • Customize Telemetry: Write custom code to collect additional telemetry data that can help you better understand your application's behavior.
  • Secure Your Data: Ensure that you secure your telemetry data by implementing appropriate security measures.

7. Conclusion

ASP.NET Core Application Insights is a powerful tool that provides comprehensive monitoring and diagnostic capabilities for ASP.NET Core applications. By using Application Insights, developers can gain insights into the performance and health of their applications, diagnose and fix issues proactively, and improve the overall user experience. With its rich set of features and ease of integration, Application Insights is an essential tool for any ASP.NET Core developer.

Step-by-Step Guide: Setting Up ASP.NET Core Application Insights

Navigating the intricacies of integrating Azure Application Insights into your ASP.NET Core application might feel daunting at first. However, with a structured approach, you can seamlessly monitor and diagnose the performance and usage of your application. This step-by-step guide will walk you through the entire process, from setting up the application to observing the data flow.

Prerequisites

  1. An Azure Account: Ensure you have an active Azure subscription to create Application Insights resources.
  2. Visual Studio 2019 or Later: Download and install the Community, Professional, or Enterprise edition of Visual Studio for development.
  3. .NET SDK: Make sure you have the .NET SDK installed. You can verify this by running dotnet --version in your command line interface.

Step 1: Create an ASP.NET Core Web Application

  1. Launch Visual Studio and select "Create a new project" from the start window.
  2. Choose the "ASP.NET Core Web App (Model-View-Controller)" template.
    • Name your project (e.g., MyApp), and click "Create".
  3. In the next window, ensure you select the version of .NET Core (e.g., .NET 6.0), select "Enable Docker Support" (optional), and click "Create".

Step 2: Create an Application Insights Resource in Azure

  1. Navigate to the Azure portal and log in with your Azure subscription.
  2. Click on "Create a resource" and search for "Application Insights".
  3. Select "Application Insights" and click "Create".
  4. Configure the new resource:
    • Name: Provide a unique name for your Application Insights resource (e.g., MyApp-AppInsights).
    • Resource Group: Select or create a new resource group.
    • Region: Choose the region closest to your users.
  5. Click "Review + create" and then "Create" to provision the resource.

Step 3: Configure Application Insights in Your ASP.NET Core Project

Back in Visual Studio, follow these steps:

  1. Install Application Insights: Open NuGet Package Manager Console and run the following command:
    Install-Package Microsoft.ApplicationInsights.AspNetCore
    
  2. Configure Services and Middleware:
    • Open Program.cs (in .NET 6 and later).
    • Add Azure Application Insights to the services collection and use it as middleware:
      using Microsoft.ApplicationInsights.Extensibility;
      
      var builder = WebApplication.CreateBuilder(args);
      
      // Add services to the container.
      builder.Services.AddControllersWithViews();
      
      // Add Application Insights telemetry.
      builder.Services.AddApplicationInsightsTelemetry(builder.Configuration);
      
      var app = builder.Build();
      
      // Configure the HTTP request pipeline.
      if (!app.Environment.IsDevelopment())
      {
          app.UseExceptionHandler("/Home/Error");
          app.UseHsts();
      }
      
      app.UseHttpsRedirection();
      app.UseStaticFiles();
      
      app.UseRouting();
      
      app.UseAuthorization();
      
      app.MapControllerRoute(
          name: "default",
          pattern: "{controller=Home}/{action=Index}/{id?}");
      
      app.Run();
      
  3. Set Application Insights Connection String:
    • In the Azure portal, navigate to your Application Insights resource and go to "Overview".
    • Copy the "Instrumentation Key".
    • Open appsettings.json in your project and add the following:
      {
        "ApplicationInsights": {
          "InstrumentationKey": "YOUR_INSTRUMENTATION_KEY"
        }
      }
      
    • Alternatively, you can add the connection string to "Configuration" > "Application Settings" in the Azure portal.

Step 4: Set Route and Run the Application

  1. Define a Route (Optional):
    • If you haven’t already, create a new route for testing. Modify HomeController.cs:
      public class HomeController : Controller
      {
          private readonly ILogger<HomeController> _logger;
      
          public HomeController(ILogger<HomeController> logger)
          {
              _logger = logger;
          }
      
          public IActionResult Index()
          {
              _logger.LogInformation("Visited Index page");
              return View();
          }
      
          public IActionResult Privacy()
          {
              _logger.LogInformation("Visited Privacy page");
              return View();
          }
      
          [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
          public IActionResult Error()
          {
              return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
          }
      
          public IActionResult TestRoute()
          {
              _logger.LogInformation("Visited TestRoute page");
              return View();
          }
      }
      
  2. Add a View for the New Route:
    • Navigate to Views/Home and create a new view TestRoute.cshtml.
  3. Run the Application:
    • Press F5 or click "Start" in Visual Studio to run your application.
    • Visit various routes, including the new TestRoute to generate some telemetry data.

Step 5: Monitor Data Flow in Application Insights

  1. Navigate to Application Insights Portal:
    • Go to the Azure portal and open your Application Insights resource.
  2. Explore Different Telemetry Data:
    • Overview: Check out the live metrics dashboard to see real-time data.
    • Metrics: Explore pre-built charts and create custom metrics and metric charts.
    • Failures: View and analyze exceptions and failed requests.
    • Usage: Analyze user activity and application usage trends.
    • Performance: Examine the performance of your application and identify slow endpoints.

Conclusion

By following the above steps, you have successfully integrated Azure Application Insights into your ASP.NET Core application. This integration allows you to monitor and diagnose the performance and usage of your app in real-time, providing deep insights to improve app quality and user experience. As you continue to develop and deploy your application, keep leveraging Application Insights to make informed decisions and optimize your application continually. Happy coding!

Top 10 Questions and Answers on ASP.NET Core Application Insights

1. What is Application Insights? Answer: Application Insights is a tool provided by Microsoft to monitor live applications. It helps developers to monitor, analyze, and understand the application's performance and usage. Application Insights can be used for a wide variety of applications, including ASP.NET Core applications, to get insights like application health, performance bottlenecks, usage trends, and more.

2. How do you integrate Application Insights into an ASP.NET Core application? Answer: To integrate Application Insights into an ASP.NET Core application, follow these steps:

  • Install the NuGet package: Use the NuGet Package Manager to install Microsoft.ApplicationInsights.AspNetCore.
  • Configure services: In the Program.cs or Startup.cs file, call services.AddApplicationInsightsTelemetry(); to register the Application Insights services.
  • Configure Application Insights Key: The ApplicationInsights key is usually configured in your appsettings.json file under ApplicationInsights as InstrumentationKey.
  • Publish and deploy your application. Once the app is running, it will start sending data to Application Insights.

3. What types of data can you monitor using Application Insights? Answer: Application Insights can monitor a wide range of data, including:

  • Requests: Information about user requests to the application.
  • Performance: Metrics like server performance, response time, and dependencies.
  • Exceptions: Errors and exceptions that occur in the application.
  • Custom metrics: Any custom data you choose to track using Application Insights SDK.
  • User behavior: User activity, page views, and session information.
  • Usage: How users engage with the application over time.

4. How do you configure custom instrumentation in Application Insights for an ASP.NET Core application? Answer: Custom instrumentation involves adding your own telemetry to track specific aspects of your application's behavior. Here’s how to do it:

  • Add the TelemetryClient: Inject TelemetryClient through dependency injection into your services or controllers.
  • Track custom events: Use telemetryClient.TrackEvent(eventName, properties, metric); to track custom user actions or significant application events.
  • Track metrics: Use telemetryClient.GetMetric(metricName).TrackValue(metric); to track custom metrics.
  • Track exceptions: Use telemetryClient.TrackException(exception); to log custom exceptions.

5. How can you use Application Insights logs to diagnose application issues? Answer: Diagnosing issues using Application Insights logs involves searching and analyzing logs to identify trends, exceptions, and performance issues. To do this:

  • Navigate to the Logs (Analytics) section: Inside the Application Insights resource in the Azure portal.
  • Use Kusto Query Language (KQL): To write queries to filter and search through logs.
    • Example: requests | where duration > 5000 to find requests that took more than 5 seconds to process.
    • Example: exceptions.summary.message to view exception messages.
    • Example: traces to see all custom log messages.
  • Correlate logs: You can correlate different types of logs (exceptions, dependencies, custom telemetry) by checking the operation_Id which is unique to every request.

6. What role do availability tests play in Application Insights? Answer: Availability tests in Application Insights help ensure your application is up and running from user's locations around the world. It provides a global view of how your application is performing, simulating user activity and reporting on any issues it encounters.

  • Create a test: Go to the Application Insights resource in the Azure portal and select "Availability".
  • Configure tests: Set up URL-based tests which send simulated HTTP requests to a URL at configured intervals (every 5, 10, etc., minutes).
  • Analyze results: The results will be displayed in the Azure portal, showing how often the test succeeded or failed.

7. How do you use Application Insights to optimize application performance? Answer: Optimizing application performance using Application Insights involves several steps:

  • Analyze metrics: Monitor metrics such as request latency, server response time, and CPU, memory, and disk usage.
  • Identify bottlenecks: Use the Performance blade to find slow server responses, slow or failed external dependencies, and high resource usage.
  • Use diagnostic searches: Filter and search through requests, exceptions, and dependencies to identify specific issues.
  • Implement fixes: Based on the collected data, implement code changes or infrastructure optimizations.
  • Monitor and iterate: Continuously monitor your application's performance and make adjustments as necessary.

8. Can you enable or disable Application Insights telemetry at runtime without redeploying your application? Answer: Yes, you can enable or disable Application Insights telemetry at runtime without redeploying your application.

  • Use TelemetryConfiguration: The TelemetryConfiguration instance contains settings that control what telemetry is collected.
  • Set TelemetryChannel to null: To disable telemetry, set the TelemetryConfiguration.Active.TelemetryChannel to null.
  • Set TelemetryChannel back to valid channel: To re-enable, set it back to a valid configuration.
  • Note: It’s best practice to use feature flags or configuration settings in your appsettings.json rather than changing the Telemetry Channel directly in code.

9. How can you secure your Application Insights data? Answer: Securing Application Insights data involves several best practices:

  • Instrumentation Key Privacy: Do not expose the instrumentation key publicly. Treat it like a sensitive API key.
  • Network Security: Ensure that only authorized IP addresses can send data to your Application Insights instance. Use the IP-based access restriction feature.
  • Role-Based Access Control (RBAC): Use RBAC to restrict who can view or manage the Application Insights resource in the Azure portal.
  • Data retention and purge policies: Define how long to retain telemetry data and configure purge policies as needed.
  • Data encryption: Ensure data is encrypted both in transit and at rest.

10. How do you troubleshoot common issues with Application Insights integration in ASP.NET Core? Answer: Troubleshooting common issues with Application Insights in ASP.NET Core includes:

  • Telemetry not appearing in portal: Ensure that the InstrumentationKey is correct and valid.
  • Telemetry collection stopped: Check the TelemetryConfiguration and ensure TelemetryChannel is active.
  • Errors in logs: Review application logs for exceptions related to Application Insights SDK or configuration.
  • Performance issues: Check for slow server response times, high resource usage, or failed dependencies.
  • Incorrect data: Verify your telemetry instrumentation and ensure that events, metrics, and exceptions are being logged correctly.

By following these steps and best practices, you can effectively monitor and optimize your ASP.NET Core applications with Application Insights, enhancing both the performance and health of your application.