Skip to main content

How to Add a Content-Security-Policy Header in ASP.NET Core (C#)

· 7 min read
Jagdish Kumawat
Founder @ Dewiride

A Content-Security-Policy header tells the browser what a page may do and who may show it. In ASP.NET Core you add it with a few lines of middleware, and it then goes out with every response, your static files included. This guide adds one with the frame-ancestors rule and shows the browser obeying it.

Syntax​

Program.cs
app.Use(async (context, next) =>
{
context.Response.Headers.ContentSecurityPolicy = "<policy>";
await next(context);
});
PartWhat it does
app.Use(...)Adds a step, a middleware, that every request passes through
context.Response.Headers.ContentSecurityPolicyThe response's Content-Security-Policy header
"<policy>"The rules, such as frame-ancestors 'self'
await next(context)Passes the request on, so the rest of the app can answer it

The header is set before next runs, so it's already in place when whatever comes later, a route or a static file, writes the response.

A policy is one or more directives, separated by semicolons. The one this guide uses is frame-ancestors, which MDN's frame-ancestors reference describes like this: The HTTP Content-Security-Policy (CSP) frame-ancestors directive specifies valid parents that may embed a page using frame, iframe, object, or embed. Its value 'self' stands for the page's own origin: MDN's CSP reference says 'self' allows the same origin as the document, and an origin is a scheme, a host and a port together, such as http://localhost:5125.

The Example​

An app called CspDemo serves two pages from wwwroot. hello.html says Hello from inside the frame!, and frame.html shows hello.html inside an <iframe>, a frame that displays another page. With frame-ancestors 'self' on every response, the frame works when frame.html comes from the same site as hello.html, and is blocked when it comes from another.

Prerequisites​

  • The .NET 10 SDK. Check with dotnet --version. This guide used 10.0.404.

Step 1: Create the App and Its Pages​

Terminal
dotnet new web -n CspDemo
cd CspDemo

Create a wwwroot folder with the page to protect:

wwwroot/hello.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Hello</title>
</head>
<body>
<p>Hello from inside the frame!</p>
</body>
</html>

And the page that shows it in a frame. Use your app's port, from Properties/launchSettings.json, in place of 5125:

wwwroot/frame.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Frame test</title>
</head>
<body>
<p>This page shows hello.html in a frame:</p>
<iframe src="http://localhost:5125/hello.html" width="320" height="80"></iframe>
</body>
</html>

Step 2: Add the Header​

Replace Program.cs:

Program.cs in a macOS-style code window: an app.Use middleware that sets context.Response.Headers.ContentSecurityPolicy to frame-ancestors 'self' and then awaits next(context), followed by app.MapStaticAssets() and app.Run().

Program.cs
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

// Every response says which pages may show it in a frame: only pages from this site.
app.Use(async (context, next) =>
{
context.Response.Headers.ContentSecurityPolicy = "frame-ancestors 'self'";
await next(context);
});

app.MapStaticAssets();

app.Run();
  • app.Use runs the code for every request that reaches the app.
  • ContentSecurityPolicy is a ready-made property for the header, so you don't have to type its name as text.
  • app.MapStaticAssets() serves the pages in wwwroot. Static files don't run any code of their own, so a middleware is how they get a header like this one. Microsoft's static files guide lists Set HTTP response headers among the things MapStaticAssets doesn't do.

Step 3: Check the Header​

Run the app:

Terminal
dotnet run

In a second terminal, ask for hello.html and print only the headers. -I sends a HEAD request, which returns the headers without the page:

Terminal
curl -I http://localhost:5125/hello.html
Output
HTTP/1.1 200 OK
Content-Type: text/html
Date: Thu, 03 Dec 2026 09:02:18 GMT
Server: Kestrel
Accept-Ranges: bytes
Cache-Control: no-cache
ETag: "pq1JX4uLHV/71MA0zwra3MfBYBwoBOp/p2/R/wuZSj8="
Last-Modified: Thu, 03 Dec 2026 08:40:32 GMT
Vary: Accept-Encoding
Content-Security-Policy: frame-ancestors 'self'

The last line is the new header, on a static file.

Step 4: Open the Frame from the Same Site​

Open http://localhost:5125/frame.html in a browser. The page and the frame both come from http://localhost:5125, so 'self' allows it:

A page that says This page shows hello.html in a frame:, with a frame below it showing Hello from inside the frame!

Step 5: Open the Frame from Another Site​

Now open the same page through http://127.0.0.1:5125/frame.html. It's the same app, but to a browser 127.0.0.1 and localhost are different hosts, so this page comes from another origin. The frame still asks for http://localhost:5125/hello.html, and this time the browser blocks it:

The same page opened from 127.0.0.1: the frame is grey and shows only a sad-page icon instead of Hello from inside the frame!

The browser's console, which you open with F12 in Chrome and Edge, says why:

Console
Framing 'http://localhost:5125/' violates the following Content Security Policy directive: "frame-ancestors 'self'". The request has been blocked.

That's the header at work: only pages from hello.html's own origin may frame it. To let another site frame your pages, list it in the directive, such as frame-ancestors 'self' https://partner.example.com.

Common Mistakes​

MistakeWhat happensDo this instead
Setting the header after await next(context)The response may already be on its way, and changing headers then throwsSet it before calling next
Leaving out await next(context)Every request ends in your middleware with an empty responseAlways pass the request on
Writing self without the single quotesThe browser reads it as a host named selfWrite 'self', quotes included
Putting frame-ancestors in a <meta> tagIt's ignored thereSend it as a response header

Troubleshooting​

SymptomLikely causeFix
curl -I shows no Content-Security-Policy lineThe app wasn't restarted after the changeStop it with Ctrl+C and run dotnet run again
A frame shows a sad-page icon and the console mentions frame-ancestorsThe page that frames it isn't in the directive's listAdd that page's origin to frame-ancestors
The frame is blocked on your own siteThe framing page uses another host or port, such as 127.0.0.1 instead of localhostUse the same origin, or list both

FAQ​

Can I set several directives at once?​

Yes, separate them with semicolons in the same header, such as frame-ancestors 'self'; img-src 'self'. Each one controls something different.

What about X-Frame-Options?​

It's the older header for the same job, with fewer choices. MDN's frame-ancestors reference compares the two: Setting this directive to 'none' is similar to X-Frame-Options: deny (which is also supported in older browsers). frame-ancestors can also list several sites.

Conclusion​

A small app.Use middleware that sets context.Response.Headers.ContentSecurityPolicy before calling next puts a Content-Security-Policy header on every response, static files included. With frame-ancestors 'self', a page from the same site can show your pages in a frame, and a page from any other site is blocked, with the reason in the browser's console.

Additional Resources​