dahui
dahui

Reputation: 2166

Web.config http header does not apply to dot net app

I'm trying to add some HTTP headers to all the HTTP responses served by my application.

I added a Web.config file as below:

<?xml version="1.0" encoding="utf-8" ?>
  <configuration>
    <system.webServer>
      <httpProtocol>
        <customHeaders>
          <add name="Content-Security-Policy" value="default-src 'self' some urls...;
           form-action some url... https:;
           upgrade-insecure-requests;" />

          <add name="Strict-Transport-Security" value="max-age=31536000" xdt:Transform="Insert" />

        </customHeaders>
      </httpProtocol>
    </system.webServer>
  </configuration>

I am using appveyor for building and octopus for deploying.

I tried to add an ItemGroup and Content tag to include the Web.config in a project, but got an error saying there was a duplicate, so I think the Web.config is already included when building.

When I try and access a page on my site, the HTTP headers have not been added.

Upvotes: 0

Views: 553

Answers (1)

dahui
dahui

Reputation: 2166

Thanks for the comments guys, particularly Panagiotis who pointed out dot net core doesn't use web config.

I ended up solving this by adding a task to add the header in StartUp.Configure, as copied from this answer.

app.Use(
    next =>
    {
        return async context =>
        {
            var stopWatch = new Stopwatch();
            stopWatch.Start();
            context.Response.OnStarting(
                () =>
                {
                    stopWatch.Stop();
                    context.Response.Headers.Add("X-ResponseTime-Ms", stopWatch.ElapsedMilliseconds.ToString());
                    return Task.CompletedTask;
                });

            await next(context);
        };
    }
);

Upvotes: 0

Related Questions