Search code examples
corsnancy

NancyFx not returning CORS for OPTIONS requests


At the moment i'm overriding the application startup in the autofac boostrapper to add in the headers below.

protected override void ApplicationStartup(ILifetimeScope container, IPipelines pipelines)
        {
            pipelines.AfterRequest.AddItemToEndOfPipeline(ctx =>
            {
                ctx.Response
                    .WithHeader("Access-Control-Allow-Origin", "*")
                    .WithHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
                    .WithHeader("Access-Control-Allow-Headers", "Accept, Origin, Content-Type, Authorization");
            });

            base.ApplicationStartup(container, pipelines);
        }

on all main routes the headers are correctly attached. However when an OPTIONS pre-flight request is sent from chrome, postman or fiddler the headers are not attached.

Here's a typical get call:

Get request and response from Nancy

Here's the browser request

enter image description here

Now in the browser request i'm getting back the wrong set of Allow.

For context, i'm currently using the clinteastwood release, but had this in the stable version too. I'm leveraging the AutofacBootstrapper, Owin & Owin.StatelessAuth.

I also tried installing Microsoft.Owin.Cors and using app.UseCors(CorsOptions.AllowAll); with no success

I'm obviously doing something wrong, I'm just not sure what...

Can anyone explain this behaviour?


Solution

  • For those interested, an obvious answer would be placing the following in the web.config.

    <system.webServer>
      <httpProtocol>
        <customHeaders>
          <add name="Access-Control-Allow-Origin" value="*" />
          <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
          <add name="Access-Control-Allow-Headers" value="Accept, Origin, Content-Type, Authorization" />
        </customHeaders>
      </httpProtocol>
    </system.webServer>
    

    But i'm more curious about the behaviour or my implementation as to where i've gone wrong