首页 > 解决方案 > 网络核心 Webapi/SignalR 应用程序被 CORS 策略阻止(带有网络框架 4.7.2 的网络核心 5。FE 消费者)

问题描述

我有一个网络框架 4.7.2 FE,我想使用一个新的 netcore 5 webapi/signalR 应用程序。

目前,我在本地 IIS ( https://local.redacted.com ) 下的 VS2017 中的 FE 和 VS2019 IIS Express 下的机器上运行,两者都使用播放/调试按钮。

我已经为 netcore 安装了 cors nuget,并且在我的启动中具有以下内容:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(c =>
            {
                c.AddPolicy(
                    "AllowCCORSOrigin",
                    options => options.WithOrigins("https://local.redacted.com/")
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .AllowCredentials());
            });
        services.AddControllers();
        services.AddSingleton<KillChecker>();
        services.AddHttpContextAccessor();
        services.AddSignalR().AddMessagePackProtocol();
        services.AddSignalR(
            o =>
                {
                    o.EnableDetailedErrors = true;
                });
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseFileServer(); //needed?
        app.UseStaticFiles();
        app.UseRouting();

        app.UseCors(builder =>
            {
                builder
                    .WithOrigins("https://local.redacted.com/")
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials();
            });
        
        app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapHub<KillHub>("/killhub");
            });
    }
}

我还装饰了我的 Launch 控制器:

[Route("[controller]"), EnableCors()]
public class LaunchController : Controller

从 FE 应用程序中,我在运行 JS 时收到以下 CORS 错误:

const options = {
    method: "POST",
    body: JSON.stringify(params),
    headers: {
        'content-type': "application/json"
    }
};
fetch("https://localhost:60907/Launch", options)
    .then(response => response.json())
    .then(data => console.log(data))
    .then(console.log('lift off'));

CORS 策略已阻止从源“https://localhost:60907/Launch”获取从“https://local.redacted.com”获取的访问权限:对预检请求的响应未通过访问控制检查:没有“访问权限” -Control-Allow-Origin' 标头存在于请求的资源上。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。

标签: javascript.net-corebrowsercorswebapi

解决方案


推荐阅读