Is it possible to enable CORS using NancyFX?

前端 未结 3 1564
日久生厌
日久生厌 2020-12-23 09:55

I have an API service made with NancyFX, and a couple of front-end developers creating an SPA JS client against this API.

We would like to test the client side code

3条回答
  •  星月不相逢
    2020-12-23 10:56

    If your HTTP request is simple then Phill's answer will suffice, but if the request is not so simple, the browser will send a preflight check. The preflight check is an OPTIONS HTTP request and this has to be handled too.

    Here is an extension method to configure CORS:

    public static class MyNancyExtension
    {
        public static void EnableCORS(this Nancy.Bootstrapper.IPipelines pipelines)
        {
            pipelines.AfterRequest.AddItemToEndOfPipeline(ctx =>
            {
                if (ctx.Request.Headers.Keys.Contains("Origin"))
                {
                    var origins = "" + string.Join(" ", ctx.Request.Headers["Origin"]);
                    ctx.Response.Headers["Access-Control-Allow-Origin"] = origins;
    
                    if (ctx.Request.Method == "OPTIONS")
                    {
                        // handle CORS preflight request
    
                        ctx.Response.Headers["Access-Control-Allow-Methods"] =
                            "GET, POST, PUT, DELETE, OPTIONS";
    
                        if (ctx.Request.Headers.Keys.Contains("Access-Control-Request-Headers"))
                        {
                            var allowedHeaders = "" + string.Join(
                                ", ", ctx.Request.Headers["Access-Control-Request-Headers"]);
                            ctx.Response.Headers["Access-Control-Allow-Headers"] = allowedHeaders;
                        }
                    }
                }
            });
        }
    }
    

    To enable CORS call this extension method in the bootstrapper:

    protected override void ApplicationStartup(Nancy.TinyIoc.TinyIoCContainer container, Nancy.Bootstrapper.IPipelines pipelines)
    {
        base.ApplicationStartup(container, pipelines);
    
        pipelines.EnableCORS();
    }
    

    Please note it is not extending NancyModule because OPTIONS is handled outside of module (also here).

提交回复
热议问题