Skip to content
MDView as Markdown

ASP.NET Core

Microsoft's CSP guidance for ASP.NET Core is written around Blazor, and it demonstrates the policy as a <meta> tag. That matters more than it sounds, because a <meta> tag policy cannot report - so if you want violation reports, you need the header instead.

What ASP.NET Core gives you

  • No built-in CSP middleware. You set the header yourself in the request pipeline.
  • For Blazor, documented starting policies per hosting model, including 'wasm-unsafe-eval' for the client-side Mono runtime and hashes for the framework's own inline scripts.
  • Blazor Web Apps on .NET 8 and later automatically send Content-Security-Policy: frame-ancestors 'self', configurable via ContentSecurityFrameAncestorsPolicy.
  • Guidance on resolving violations with either Subresource Integrity - which Microsoft recommends - or a cryptographic nonce.

Setting the header

Middleware is the straightforward route, and unlike a <meta> tag it can carry a reporting directive. Your URL comes from the Setup page:

app.Use(async (context, next) =>
{
    context.Response.Headers.Append("Content-Security-Policy-Report-Only",
        "default-src 'self'; object-src 'none'; " +
        "report-uri https://abc123.report-uri.com/r/d/csp/reportOnly");
    await next();
});

Things to watch for

  • A <meta> tag policy silently drops report-uri, report-to, frame-ancestors and sandbox. Microsoft's own documentation says so. Every example in their Blazor guide uses a <meta> tag, so it is easy to follow the guidance exactly and end up with a policy that can never tell you what it blocked.
  • A CSP applied in <head> interferes with local development - Browser Link and the browser refresh script get blocked. Microsoft's fix is to gate the policy on !Env.IsDevelopment().
  • Blazor Web Apps render an inline import map and, in some versions, an inline onclick handler in the NavMenu component. Both need a hash, a nonce, or to be moved out of line.
  • If you gate the policy on environment, remember that report-only in production is still production. Ship the report-only header everywhere you would ship the enforcing one.

Official documentation

Microsoft - Enforce a Content Security Policy for ASP.NET Core Blazor

Start Monitoring with Report URI

Already using us for CSP? Find your report-uri value on Setup, or view your CSP reports.

New to Report URI? Create an account and grab your report-uri value from the Setup page.

Start your free trial