X-Content-Type-Options is an HTTP response header that keeps browsers from treating a response as a type different from its declared media type. Set it to "nosniff" to reduce the risk of harmful files being executed or downloaded. section 12.1.4
Configure the header in the API startup pipeline:
- Place the configuration in Program.cs alongside the other HTTP security headers. section 12.1.4
- Apply it through custom middleware because this header does not use the built-in HSTS middleware. section 12.1.4
- Register it for nondevelopment environments, where security headers are enabled without complicating localhost development. section 12.1.4
Listing 12.1 Program.cs file: HTTP security headers
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
else
{
// HTTP Security Headers
app.UseHsts(); #1
app.Use(async (context, next) =>
{
context.Response.Headers.Add("X-Frame-Options",
"sameorigin"); #2
context.Response.Headers.Add("X-XSS-Protection",
"1; mode=block"); #3
context.Response.Headers.Add("X-Content-Type-Options",
"nosniff"); #4
context.Response.Headers.Add("Content-Security-Policy",
"default-src ' self' ;"); #5
context.Response.Headers.Add("Referrer-Policy",
"strict-origin"); #6
await next();
});
}
Inspect the Program.cs listing to see X-Content-Type-Options added with the value "nosniff" inside response-header middleware. section 12.1.4

