How to Implement Google Analytics in ASP.NET C#

Cody Schneider8 min read

Tracking how users interact with your ASP.NET application provides the essential feedback you need to grow and improve. This guide walks you through implementing Google Analytics 4 in C#, covering both the simple client-side setup and the more powerful server-side approach.

GraphedGraphed

Still Building Reports Manually?

Watch how growth teams are getting answers in seconds — not days.

Watch Graphed demo video

First, Get Your Google Analytics 4 Details

Before you write any code, you need a place within Google Analytics to send your data. This means creating a GA4 "Property" and a "Web Data Stream." If you already have one, you can skip to the next section.

Here’s the quick rundown:

  1. Sign in to Google Analytics: Navigate to the Google Analytics homepage.
  2. Navigate to Admin: Click the gear icon in the bottom-left corner.
  3. Create a Property: In the "Property" column, click "Create Property" and follow the setup wizard. You'll give it a name, select your time zone, and choose your currency.
  4. Create a Data Stream: After creating the property, you'll be prompted to set up a data stream. Choose "Web" as the platform.
  5. Enter Your Website Details: Input your website's URL (e.g., https://www.yourapp.com) and give the stream a name.
  6. Copy Your Measurement ID: Once created, Google will display your "Measurement ID," which looks like G-XXXXXXXXXX. This ID is crucial - it tells the tracking code which GA4 property to send data to. Keep it handy.

With your Measurement ID copied, you're ready to add the tracking code to your ASP.NET application.

The Standard Method: Client-Side Tracking with Gtag.js

This is the most common and direct way to get Google Analytics running. It uses a JavaScript snippet (known as gtag.js) that runs in the user's browser to track actions like page views, clicks, and scrolls automatically. This method is perfect for capturing front-end user behavior.

Where to Add the Tracking Code

For tracking to work on every page, you should place the gtag.js snippet in a shared layout file that is used across your entire application. This way, you don’t have to add it to every single view or page manually.

  • For ASP.NET MVC or Razor Pages, this is usually _Layout.cshtml in the Views/Shared directory.
  • For ASP.NET Web Forms, this would be your Site.Master page.

The script should be placed inside the <head>, <head>, tag of your HTML.

Adding Gtag.js in an ASP.NET MVC Application

Hardcoding your Measurement ID directly into the script isn't ideal. A better practice is to store it in your application's configuration, such as the appsettings.json file, and inject it into your layout page.

Step 1: Add the ID to appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "GoogleAnalytics": {
    "MeasurementId": "G-XXXXXXXXXX" 
  }
}

Remember to replace G-XXXXXXXXXX with your actual Measurement ID.

Step 2: Inject Configuration into _Layout.cshtml

At the top of _Layout.cshtml, inject the IConfiguration service:

@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration

Then, inside the <head>, add the gtag.js script, using the injected configuration:

<script async src="https://www.googletagmanager.com/gtag/js?id=@Configuration["GoogleAnalytics:MeasurementId"]"></script>
<script>
  window.dataLayer = window.dataLayer || [],
  function gtag(){dataLayer.push(arguments),}
  gtag('js', new Date()),

  gtag('config', '@Configuration["GoogleAnalytics:MeasurementId"]'),
</script>
GraphedGraphed

Still Building Reports Manually?

Watch how growth teams are getting answers in seconds — not days.

Watch Graphed demo video

Verify Your Implementation

After deploying your application, you can quickly check if the tracking is working:

  • Google Analytics Realtime Report: Open your GA4 property and navigate to Reports > Realtime. When you visit your website, you should see your activity appear in the report within a minute or two.
  • Browser Developer Tools: Open your browser's developer tools (usually F12), go to the "Network" tab, and filter for "collect". As you navigate your site, you should see requests being sent to Google Analytics.

Advanced Method: Server-Side Tracking with the Measurement Protocol

Sometimes, tracking events from the user's browser isn't enough. You might need to record actions that happen on the server, well away from the user interface. This is where the Measurement Protocol comes in handy.

When to Use Server-Side Tracking

The Measurement Protocol lets you send data directly to Google Analytics from your server via HTTP requests. It's ideal for tracking:

  • Offline Events: A recurring subscription is renewed, or a lead status is updated in your CRM.
  • Server-Side Validations: A user submits a form, but you only want to track the conversion after your C# backend successfully validates and processes the data.
  • Guaranteed Delivery: Overcomes issues where client-side JavaScript might be blocked by ad-blockers or browser privacy settings.
  • Backend Processes: An item's stock level drops below a certain threshold, triggering an internal event you want to track for business intelligence.

Sending Events from a C# Backend

To send server-side events, you'll need two things from your GA4 Web Data Stream settings: your Measurement ID (G-XXXXXXXXXX) and an API Secret.

Step 1: Get an API Secret

In your GA4 property, navigate to Admin > Data Streams > [Your Web Stream]. Under the "Events" section, find "Measurement Protocol API secrets" and create a new secret. Copy this value securely.

Step 2: Store Your Credentials Securely

Add your API Secret to your appsettings.json file. For production, it is highly recommended to use the .NET Secret Manager or Azure Key Vault to store secrets.

"GoogleAnalytics": {
  "MeasurementId": "G-XXXXXXXXXX",
  "ApiSecret": "YOUR_API_SECRET_HERE"
}
GraphedGraphed

Still Building Reports Manually?

Watch how growth teams are getting answers in seconds — not days.

Watch Graphed demo video

Create a C# Helper to Send Events

Let's create a reusable service that can send events to GA4. This example uses HttpClient to send a lead_generated event.

Important: You need the client_id to link server-side events with a specific user session. To do this, capture the client_id on the front end and pass it to your backend.

// A simple service to send events to GA4
public class GoogleAnalyticsService
{
    private readonly HttpClient _httpClient,
    private readonly IConfiguration _configuration,
    private const string GA4_URL = "https://www.google-analytics.com/mp/collect",

    public GoogleAnalyticsService(HttpClient httpClient, IConfiguration configuration)
    {
        _httpClient = httpClient,
        _configuration = configuration,
    }

    public async Task TrackEvent(string eventName, string clientId, Dictionary<string, object> eventParams = null)
    {
        var measurementId = _configuration["GoogleAnalytics:MeasurementId"],
        var apiSecret = _configuration["GoogleAnalytics:ApiSecret"],

        if (string.IsNullOrEmpty(measurementId) || string.IsNullOrEmpty(apiSecret))
        {
            // Log this warning, don't track if not configured
            return,
        }

        var requestBody = new
        {
            client_id = clientId,
            non_personalized_ads = false,
            events = new[]
            {
                new
                {
                    name = eventName,
                    @params = eventParams ?? new Dictionary<string, object>()
                }
            }
        },

        var jsonPayload = System.Text.Json.JsonSerializer.Serialize(requestBody),
        var content = new StringContent(jsonPayload, System.Text.Encoding.UTF8, "application/json"),

        var response = await _httpClient.PostAsync($"{GA4_URL}?api_secret={apiSecret}&measurement_id={measurementId}", content),

        // Optional: Log response for debugging
        // response.EnsureSuccessStatusCode(),
    }
}

Register this service in your Program.cs or Startup.cs:

builder.Services.AddHttpClient<GoogleAnalyticsService>(),

Use it in your controller after a successful operation:

// Example usage in an MVC controller action
[HttpPost]
public async Task<IActionResult> SubmitContactForm(ContactFormModel model)
{
    if (ModelState.IsValid)
    {
        // ... save form data to a database ...

        // Send a server-side event to Google Analytics
        var eventParams = new Dictionary<string, object>
        {
            {"form_type", "contact"},
            {"user_engagement_source", "web"}
        },
        await _gaService.TrackEvent("lead_generated", model.ClientId, eventParams),

        return RedirectToAction("ThankYou"),
    }

    return View(model),
}
GraphedGraphed

Still Building Reports Manually?

Watch how growth teams are getting answers in seconds — not days.

Watch Graphed demo video

Hybrid Model: The Best of Both Worlds

For most applications, a hybrid approach provides the most comprehensive data. You use client-side Gtag.js for general page views and engagement, then fire high-value events from your server for accuracy and reliability.

The key to making this work is cohesively tracking the user's journey. You do this by passing the client_id from the browser to the server whenever a key action occurs.

Capturing the Client ID with JavaScript

Add this script to your view or a global JavaScript file. It waits for the gtag function to become available, retrieves the client_id, and populates a hidden input field with the ID ga_client_id.

try {
  gtag('get', '@Configuration["GoogleAnalytics:MeasurementId"]', 'client_id', function (clientId) {
    var hiddenInput = document.getElementById('ga_client_id'),
    if (hiddenInput) {
      hiddenInput.value = clientId,
    }
  }),
} catch (e) {
  console.error("Gtag for client_id not available.", e),
}

Your HTML form would then include the hidden input:

<form asp-action="SubmitContactForm" method="post">
    <!-- other form fields -->
    <input type="hidden" id="ga_client_id" name="ClientId" />
    <button type="submit">Submit</button>
</form>

With this setup, your server receives the client ID along with the form's data, allowing you to link your server-side event perfectly to the user's session data being collected by the client-side script.

Final Thoughts

Implementing Google Analytics in your ASP.NET application gives you incredible visibility into what users are doing, what they care about, and where they're getting stuck. By choosing between client-side tracking for ease and server-side tracking for power — or combining them both — you can build a complete picture of your application's performance.

Once your data is flowing into Google Analytics, the next step is making sense of it all. Instead of spending hours in the GA interface manually building reports, we created Graphed to do the heavy lifting for you. You can connect your Google Analytics account and use plain English to ask questions like, "Show me a dashboard of user engagement on our blog pages for the last 30 days," and get real-time dashboards created in seconds, saving you time for the work that really matters.

Related Articles