liveBook · Manning

X-Content-Type-Options

As explained in Building Web APIs with ASP.NET Core

An HTTP response header that prevents browsers from interpreting content as a type different from its declared media type.

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

How Building Web APIs with ASP.NET Core covers it

How deep it goes
Defines the header’s protection and shows its middleware configuration, but defers detailed security-header coverage.
Examples
Uses Program.cs middleware to add X-Content-Type-Options with the value "nosniff" outside development.
What it assumes
Assumes a Program.cs startup pipeline and environment branching, while defining the header’s purpose before configuration.
What you can do after
Operate/configure an API response pipeline that emits the nosniff protection header in deployed environments.
How it connects
Connects HTTP security headers with response middleware, declared media types, and deployment environments.

Also explained in

Compare how 2 books explain X-Content-Type-Options →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Building Web APIs with ASP.NET Core. The section links point to the parts of the book it draws on.