Nancy + .NET Core 启用 CORS 不工作

Nancy + .NET Core enable CORS not working

我在客户端有以下请求:

$.get(getUrl)

我在后端尝试了以下方法:

Is it possible to enable CORS using NancyFX?

我也尝试过这四种方法(分别,因此注释掉):

        // protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
    // {
    //     pipelines.AfterRequest += ctx =>
    //     {
    //         ctx.Response.Headers.Add("Access-Control-Allow-Origin", "*");
    //         ctx.Response.Headers.Add("Access-Control-Allow-Headers", "*");
    //         ctx.Response.Headers.Add("Access-Control-Allow-Methods", "*");
    //     };
    // }

    protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
    {
        pipelines.AfterRequest += (ctx) =>
        {
            ctx.Response.Headers.Add("Access-Control-Allow-Origin", "*");
        };
    }

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

        // pipelines.AfterRequest.AddItemToEndOfPipeline((ctx) =>
        // {
        //     ctx.Response.WithHeader("Access-Control-Allow-Origin", "*")
        //         .WithHeader("Access-Control-Allow-Methods", "*")
        //         .WithHeader("Access-Control-Allow-Headers", "*");        
        // });

        // pipelines.AfterRequest += (ctx) =>
        // {
        //     ctx.Response.Headers.Add("Access-Control-Allow-Origin", "*");
        //     ctx.Response.Headers.Add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        // };

我什至为我的模块尝试过类似的东西:

After += (Context) =>
{
    Context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
    Context.Response.Headers.Add("Access-Control-Allow-Methods", "PUT, GET, POST, DELETE, OPTIONS");
    Context.Response.Headers.Add("Access-Control-Allow-Headers", "Content-Type, x-requested-with, Authorization, Accept, Origin");
};

所有产量相同:

XMLHttpRequest cannot load http://localhost:5000/registration/signup. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:5001' is therefore not allowed access. The response had HTTP status code 401.

401 是因为我没有传递预期的自定义 header。我只是想先解决 CORS 问题

拜托。这是一条双头蛇。我求助于尝试一个基本的 nodejs 反向代理,当它不起作用时……这一切都有意义。

我对 Nancy 采取的一些方法似乎并没有奏效,因为我有 auth 中间件代码,它在引导程序代码之前 hit/run。因此,预检请求总是会立即收到 401(它们不会发送中间件正在检查的自定义 header),并且启用 CORS 的代码永远不会被命中。

但是,另一个问题是这是本地主机。浏览器显然不允许本地主机使用 CORS。所以这里的解决方案是使用 ngrok(没有为此测试,但没有理由它不应该工作)。或者 运行 chrome 将禁用的网络安全标志设置为 false(此方法因 OS 而异)。

我尝试了后一种选择,为了解决我的 Nancy CORS 代码不是 运行 的问题,我将其全部删除并采用此处概述的标准 .NET Core CORS 方法:https://docs.microsoft.com/en-us/aspnet/core/security/cors

现在我的 Access-Control-Allow-Origin header 正在设置,chrome 运行 有点不安全。但它有效。

我认为在生产环境中我会使用像 NGINX 这样的反向代理。而这一切都将成为遥远的记忆...