为什么 AddCrossOriginWhitelistEntry 或 IsCorsEnabled 不允许使用自定义方案处理程序的 CORS?

Why does AddCrossOriginWhitelistEntry or IsCorsEnabled not allow CORS with a custom scheme handler?

上下文

我们正在使用 CefSharp (v57.0) 托管 Angular2 (v4.2) 应用程序,该应用程序在 Web 应用程序和游戏 UI 客户端之间使用共享组件。旨在让游戏客户端从 CEFSharp 容器内向服务器发出请求。

客户端游戏应用程序在从嵌入式资源加载的单个 index.html 中加载。这是基于这篇 Create A Desktop Application using Angular, Bootstrap and C# 文章。

问题

当我向服务器发出请求时,CEF 游戏客户端记录以下错误:

http://localhost:53462/Some/Api/Method. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://embedded' is therefore not allowed access.

CEF 初始化后我调用 Cef.AddCrossOriginWhitelistEntry("http://embedded", "http", "localhost:53462", true); which returns true 表示应该允许。为什么不将域列入白名单?

代码

精简资源处理程序:

public class EmbeddedResourceHandlerFactory : ISchemeHandlerFactory
{
    private Assembly assembly = null;

    public EmbeddedResourceHandlerFactory(Assembly assembly)
    {
        this.assembly = assembly;
    }

    public IResourceHandler Create(IBrowser browser, IFrame frame, string schemeName, IRequest request)
    {
        // Calculate the resource being loaded
        Uri uri = new Uri(request.Url);
        string path = uri.PathAndQuery + uri.Fragment;

        // Calculate the final path of the embedded resource
        string mime = ResourceHandler.GetMimeType(Path.GetExtension(path));
        path = $"{assembly.GetName().Name}.Views{path}".Replace("/", ".");
        if (!assembly.GetManifestResourceNames().Any(x => x.Equals(path)))
            return null;

        // Create the resource handler
        Stream stream = assembly.GetManifestResourceStream(path);
        return ResourceHandler.FromStream(stream, mime);
    }
}

注册方式如下

settings.RegisterScheme(new CefCustomScheme()
{
    SchemeName = "http",
    DomainName = "embedded",
    SchemeHandlerFactory = new EmbeddedResourceHandlerFactory(assembly),
    IsCorsEnabled = true,
});

我终于解决了。这与 CEFSharpAngular 无关。该错误具有误导性,问题是服务器未设置为允许 CORS。在我的例子中,服务器应用程序是 Asp.Net Core 并且很容易为我的 http://embedded 自定义方案处理程序启用:

1: 将Microsoft.AspNetCore.Cors nuget 包添加到服务器应用程序。

2:在Startup.cs.

的ConfigureServices方法中添加Cors服务
public void ConfigureServices(IServiceCollection services)
{
    services.AddCors();
}

3:告诉Startup.cs的Configure方法使用Cors

public void Configure(IApplicationBuilder app, IHostingEnvironment env, 
ILoggerFactory loggerFactory)
{
    app.UseCors(options => options.WithOrigins("http://embedded").AllowAnyMethod());
}