Content-Security-Policy (CSP) is an HTTP response header that tells the browser which content it may load or execute. It helps protect a web application against cross-site scripting (XSS) and other code-injection attacks. section 12.1.4
To add CSP to an ASP.NET Core API:
- In Program.cs, add the header through response-header middleware. Keep it alongside the API’s other security headers; HSTS uses its own built-in middleware. section 12.1.4
- Apply these headers outside development. Some security-header settings can cause inconvenient behavior on localhost. section 12.1.4
- After deployment, test an endpoint containing an inline script. If the page is blank, open the browser’s developer console to check whether CSP blocked the script. section 12.4.4
A blocked script and a narrow exception
The /cod/test endpoint expects a JavaScript alert, but its inline script is blocked by the initial policy. The console reports that no script-src directive was set, so default-src was used instead. A revised policy adds script-src with a nonce, and the endpoint gives its script element the matching nonce. After redeployment, the alert can run. This demonstrates the mechanism, not a general recommendation: allowing inline scripts weakens CSP’s protection and should be avoided in production unless needed. section 12.4.4
Refused to execute inline script because it violates the following Content Security Policy directive: "default-src ' self' ". Either the ‘unsafe-inline’ keyword, a hash (‘sha256-j3kW1ylRRXx1+pINyR/6EW435UHoxKSlU6fhd5xVSSk=‘), or a nonce (' nonce-...' ) is required to enable inline execution. Note also that ' script-src' was not explicitly set, so ' default-src' is used as a fallback.
The browser’s refusal message identifies the blocked inline script and explains why default-src applies. section 12.4.4
context.Response.Headers.Add("Content-Security-Policy",
"default-src ' self' ; script-src ' self' ' nonce-23a98b38c' ;");
This response-header setting shows the added script-src directive and nonce used for the exception. section 12.4.4

