Configuring ASP.NET Core Apps for Heroku
Last updated April 23, 2025
Table of Contents
Deploying ASP.NET Core applications to Heroku requires minimal setup. However, it’s essential to configure runtime behavior to align with Heroku’s routing and security model.
Detecting the Heroku Environment
Heroku sets a DYNO
environment variable on all dynos that you can use to confirm your app runs on Heroku:
var isHeroku = !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("DYNO"));
This environment variable enables you to apply Heroku-specific configurations if needed.
Handling Forwarded Headers
Heroku routes requests through a reverse proxy, forwarding requests with headers like X-Forwarded-For
and X-Forwarded-Proto
. To correctly handle client IP addresses and HTTPS detection, configure the Forwarded Headers Middleware in your Program.cs
:
using Microsoft.AspNetCore.HttpOverrides;
var builder = WebApplication.CreateBuilder(args);
builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
options.KnownNetworks.Clear();
options.KnownProxies.Clear();
});
var app = builder.Build();
// Forwarded headers must come first
app.UseForwardedHeaders();
Place UseForwardedHeaders()
as early as possible in your pipeline to ensure forwarded information processes correctly.
Enforcing HTTPS
Heroku doesn’t automatically redirect HTTP requests to HTTPS. To enforce HTTPS redirection in your app, add:
builder.Services.AddHttpsRedirection(options =>
{
options.RedirectStatusCode = StatusCodes.Status308PermanentRedirect;
options.HttpsPort = 443;
});
app.UseHttpsRedirection();
Make sure UseHttpsRedirection()
is called after UseForwardedHeaders()
.
Example
Here’s a minimal Program.cs
setup optimized for Heroku and compatible with local development:
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.Http;
var builder = WebApplication.CreateBuilder(args);
var isHeroku = !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("DYNO"));
builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
if (isHeroku)
{
options.KnownNetworks.Clear();
options.KnownProxies.Clear();
}
});
builder.Services.AddHttpsRedirection(options =>
{
if (isHeroku)
{
options.RedirectStatusCode = StatusCodes.Status308PermanentRedirect;
options.HttpsPort = 443;
}
});
var app = builder.Build();
app.UseForwardedHeaders();
app.UseHttpsRedirection();
app.MapGet("/", () => "Hello from Heroku!");
app.Run();
Summary
To successfully run ASP.NET Core apps on Heroku:
- Detect a Heroku environment with the
DYNO
environment variable. - Configure Forwarded Headers Middleware early.
- Enforce HTTPS redirection.
Use this setup to ensure your app behaves correctly and securely on Heroku.