ASP.NET Core Stripe UTM tracking: Checkout with Stripe.net
By Devendra Variya, co-founder of Virling. Published 2026-11-22, updated 2026-11-26.
In ASP.NET Core, attribution lives in whichever endpoint creates the Stripe Checkout Session: take virling_vid from Request.Cookies and set it as ClientReferenceId on Stripe.net's SessionCreateOptions. Minimal APIs, controllers and Razor Pages each reach the request a little differently, so this post shows all three.
Stripe hosts the payment page, so the campaign tags on your landing page are gone by the time the buyer pays. Virling keeps them on its side, keyed by a visitor ID that its script writes to a cookie, and credits a payment to those visits when the Checkout Session carries the ID. Payment Links and how the values appear in the Stripe dashboard are in Stripe Checkout UTM parameters; the same flow for other stacks is in Spring Boot, Go and Next.js.
Add the script to _Layout.cshtml or App.razor
The tag goes in the <head> of Pages/Shared/_Layout.cshtml for Razor Pages, Views/Shared/_Layout.cshtml for MVC, or Components/App.razor for Blazor. A self-hosted Virling serves the same file from your own server.
<!-- Pages/Shared/_Layout.cshtml --> <script defer src="https://app.virling.com/v.js" data-site="yourdomain.com"></script>
Minimal API endpoint
A minimal API handler can ask for HttpRequest as a parameter and ASP.NET Core binds it without attributes. There is no [FromCookie] binding source, so read the collection directly; TryGetValue returns false when the visitor has no cookie.
using Stripe;
using Stripe.Checkout;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<IStripeClient>(
new StripeClient(builder.Configuration["Stripe:SecretKey"]));
var app = builder.Build();
app.MapPost("/checkout", async (HttpRequest request, IStripeClient stripe) =>
{
var options = new SessionCreateOptions
{
Mode = "subscription",
LineItems = new List<SessionLineItemOptions>
{
new() { Price = "price_...", Quantity = 1 },
},
SuccessUrl = "https://yourdomain.com/thanks",
};
if (request.Cookies.TryGetValue("virling_vid", out var vid) && !string.IsNullOrEmpty(vid))
{
options.ClientReferenceId = vid;
}
var session = await new SessionService(stripe).CreateAsync(options);
return Results.Redirect(session.Url);
});
app.Run();Add the Stripe.net package from NuGet. Registering one StripeClient and passing it to SessionService keeps the key out of the static StripeConfiguration.ApiKey; read it from user secrets in development and from the Stripe__SecretKey environment variable in production. Properties you leave null on SessionCreateOptions are not sent to Stripe, so a missing cookie simply means no ClientReferenceId.
This endpoint binds nothing from the form, so the antiforgery middleware in .NET 8 and later does not ask it for a token, and a plain <form method="post" action="/checkout"> on any page works.
Controller action
In MVC or an API controller, Request is a property of the base class. Its cookie indexer returns null for a missing cookie instead of throwing:
public class CheckoutController(IStripeClient stripe) : Controller
{
[HttpPost("/checkout")]
public async Task<IActionResult> Create()
{
var options = new SessionCreateOptions
{
Mode = "subscription",
LineItems = new List<SessionLineItemOptions>
{
new() { Price = "price_...", Quantity = 1 },
},
SuccessUrl = "https://yourdomain.com/thanks",
};
var vid = Request.Cookies["virling_vid"];
if (!string.IsNullOrEmpty(vid))
{
options.ClientReferenceId = vid;
}
var session = await new SessionService(stripe).CreateAsync(options);
return Redirect(session.Url);
}
}If you register the global AutoValidateAntiforgeryTokenAttribute filter, the action rejects a form without a token with 400 Bad Request. Render the form from a Razor view with the form tag helper, which adds the hidden __RequestVerificationToken field.
Razor Pages handler
On a Razor Page, put a named POST handler on the page model of your pricing page and point the form at it with asp-page-handler. Razor Pages validate the antiforgery token on every POST, and the form tag helper inserts it for you:
// Pages/Pricing.cshtml.cs
public class PricingModel(IStripeClient stripe) : PageModel
{
public async Task<IActionResult> OnPostCheckoutAsync()
{
var options = new SessionCreateOptions
{
Mode = "subscription",
LineItems = new List<SessionLineItemOptions>
{
new() { Price = "price_...", Quantity = 1 },
},
SuccessUrl = "https://yourdomain.com/thanks",
};
var vid = Request.Cookies["virling_vid"];
if (!string.IsNullOrEmpty(vid))
{
options.ClientReferenceId = vid;
}
var session = await new SessionService(stripe).CreateAsync(options);
return Redirect(session.Url);
}
}
<!-- Pages/Pricing.cshtml -->
<form method="post" asp-page-handler="Checkout">
<button type="submit">Subscribe</button>
</form>Return Redirect, not LocalRedirect: the session URL is on checkout.stripe.com, and LocalRedirect throws for any URL outside your app.
Metadata and subscriptions in Stripe.net
If ClientReferenceId is already your own user or order ID, set the session's Metadata dictionary instead; Virling reads metadata.virling_vid first. SubscriptionData.Metadata is a different dictionary that ends up on the subscription object, which Virling does not read:
options.SubscriptionData = new SessionSubscriptionDataOptions
{
Metadata = new Dictionary<string, string> { ["plan"] = "pro" }, // not read
};
if (!string.IsNullOrEmpty(vid))
{
options.Metadata = new Dictionary<string, string> { ["virling_vid"] = vid }; // read
}Later renewals carry the first payment's channel with no extra code (see renewals), and the Stripe docs list every place Virling looks for the ID.
Testing locally and in staging
Kestrel's https://localhost:7xxx address from launchSettings.json counts as localhost, where the script stays silent unless the tag carries data-dev. Visits also have to happen on your data-site domain or a subdomain of it, so a staging slot such as staging.yourdomain.com is the place for a full run through test your setup, with an rk_test_ restricted key connected in Virling. If you changed AllowedHosts in appsettings.json, include that host. To compare the stored ID with window.virling.vid() in the console, log it after CreateAsync:
logger.LogInformation("{Id} {Ref} {Vid}", session.Id, session.ClientReferenceId,
session.Metadata?.GetValueOrDefault("virling_vid"));Common mistakes
| What you see | Cause | Fix |
|---|---|---|
| No visitor ID from a Blazor page | An interactive component's event handler has no HTTP request of its own to read cookies from | Post a form to the /checkout endpoint and read the cookie there |
| 400 Bad Request when the form is submitted | A Razor Page or a controller with antiforgery validation got a form without the token | Render the form with the form tag helper |
InvalidOperationException after the session is created | LocalRedirect refuses the checkout.stripe.com URL | Use Redirect or Results.Redirect |
| No visitor ID when a separate frontend calls the API | A cross-origin fetch sends no cookies by default | Use credentials: "include" with a CORS policy that names the origin and calls AllowCredentials(), or post a form |
| Several buyers are sent to the same Checkout Session | A GET page that creates the session is cached with [OutputCache] or [ResponseCache] | Create it in a POST handler; output caching skips POST by default |
| No visitor ID, though the browser has the cookie | The session is created in a hosted service or webhook endpoint, where there is no buyer request | Read Request.Cookies in the browser-facing endpoint and pass the value on |
A buyer whose browser blocks the script has no cookie; that payment still counts toward revenue, as Unattributed. The rest of the causes are in Unattributed revenue, and the Stripe integration page shows what Virling imports.
Frequently asked questions
How do I pass UTM parameters to Stripe Checkout in ASP.NET Core?
Pass the visitor ID rather than the tags themselves. In the endpoint that creates the session, read Request.Cookies["virling_vid"] and assign it to ClientReferenceId on SessionCreateOptions; Virling matches that ID to the UTM tags it recorded for each visit.
Does this work with MVC controllers, Razor Pages or Blazor?
Controllers and Razor Pages handlers read Request.Cookies exactly like a minimal API. Interactive Blazor components cannot, so have the checkout button post a form to a server endpoint. The Stripe.net code does not change.
ClientReferenceId or the Metadata dictionary?
Start with ClientReferenceId. If your app already uses it for its own IDs, add a virling_vid entry to the session's Metadata dictionary instead; Virling checks metadata first.
What if the visitor has no virling_vid cookie?
TryGetValue returns false and the indexer returns null, so ClientReferenceId stays unset. That is normal with a blocked script or cookieless mode, and the payment is still counted toward revenue as Unattributed.
Does the ASP.NET Core cookie consent policy hide the cookie?
No. CookiePolicyOptions.CheckConsentNeeded only stops cookies your app writes with Response.Cookies. The Virling script sets virling_vid in the browser, so it shows up in Request.Cookies whenever the browser has it.
See which campaigns bring Stripe revenue
Virling is open source under AGPL. Self-host it free, or use the hosted version with a 14-day free trial. It connects to Stripe, Paddle, Shopify, WooCommerce, Polar, LemonSqueezy, Dodo, Creem and RevenueCat.