简体   繁体   English

是否可以使用NancyFX启用CORS?

[英]Is it possible to enable CORS using NancyFX?

I have an API service made with NancyFX, and a couple of front-end developers creating an SPA JS client against this API. 我有一个使用NancyFX创建的API服务,以及一些前端开发人员针对此API创建SPA JS客户端。

We would like to test the client side code against the published server without having to publish the client code with too much frequency. 我们希望针对已发布的服务器测试客户端代码,而无需以太多频率发布客户端代码。

But, the client runs at localhost, and the server is at Windows Azure. 但是,客户端在localhost运行,服务器在Windows Azure。

Is it possible and easy to enable CORS on the NancyFX server? 在NancyFX服务器上启用CORS是否可行且容易? How can I do that? 我怎样才能做到这一点?

Thanks. 谢谢。

Its possible to do this in the bootstraper of Nancy 它可以在Nancy的bootstraper中做到这一点

protected override void RequestStartup(TinyIoCContainer container, IPipelines pipelines, NancyContext context)
    {

       //CORS Enable
        pipelines.AfterRequest.AddItemToEndOfPipeline((ctx) =>
        {
            ctx.Response.WithHeader("Access-Control-Allow-Origin", "*")
                            .WithHeader("Access-Control-Allow-Methods", "POST,GET")
                            .WithHeader("Access-Control-Allow-Headers", "Accept, Origin, Content-type");

        });

If you're using IIS to host Nancy, in this case on Windows Azure then you can just update the web.config to add the header to every request. 如果您使用IIS来托管Nancy,在本例中是在Windows Azure上,那么您只需更新web.config即可为每个请求添加标头。

This can be done by adding the following: 这可以通过添加以下内容来完成:

<system.webServer>
  <httpProtocol>
    <customHeaders>
      <add name="Access-Control-Allow-Origin" value="*" />
    </customHeaders>
  </httpProtocol>
</system.webServer>

Alternatively you can do what Sunny suggested, and if you don't like writing that every time you can add your own extension method: 或者你可以做Sunny所建议的,如果你不喜欢每次都可以添加自己的扩展方法那么写:

public static class NancyExtensions
{
    public static void EnableCors(this NancyModule module)
    {
        module.After.AddItemToEndOfPipeline(x =>
        {
            x.Response.WithHeader("Access-Control-Allow-Origin", "*");
        });
    }
}

Then you can just call this.EnableCors() in your route. 然后你可以在你的路线中调用this.EnableCors()

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. 如果您的HTTP请求很简单,那么Phill的答案就足够了,但如果请求不那么简单,浏览器将发送预检检查。 The preflight check is an OPTIONS HTTP request and this has to be handled too. 预检检查是OPTIONS HTTP请求,也必须处理。

Here is an extension method to configure CORS: 以下是配置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: 要启用CORS,请在引导程序中调用此扩展方法:

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 ). 请注意,它不会扩展NancyModule,因为OPTIONS是在模块外部处理的 (也在这里 )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM