ASP.NET Core 使用 SignalR 遇到的 CORS 问题

问题

将 SignalR 集成到 ASP.NET Core MVC 程序的时候,按照官方 DEMO 配置完成,但使用 DEMO 页面创建链接一直提示以下信息。ui

Access to XMLHttpRequest at 'http://localhost:8090/signalr-myChatHub/negotiate' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

原始代码:code

services.AddCors(op =>
{
    op.AddPolicy(MonitorStartupConsts.DefaultCorsPolicyName, set =>
    {
        set.AllowAnyOrigin()
           .AllowAnyHeader()
           .AllowAnyMethod()
           .AllowCredentials();
    });
});

缘由

出现该问题的缘由是因为 CORS 策略设置不正确形成的,原始设置我是容许全部 Origin 来源。可是因为 dotnetCore 2.2 的限制,没法使用 AllowAnyOrigin() + AllowCredentials() 的组合,只能显式指定 Origin 来源,或者经过下述方式来间接实现。blog

解决

更改 Cors 相关配置,在 CorsPolicyBuilder 提供了一个方法用于配置验证逻辑。该方法名字叫作 SetIsOriginAllowed(Func<string, bool> isOriginAllowed),这个委托会验证传入的 Origin 源,若是验证经过则返回 truerequests

在这里咱们只须要将其设置为一直返回 true 便可。
最终代码以下:string

services.AddCors(op =>
{
    op.AddPolicy(MonitorStartupConsts.DefaultCorsPolicyName, set =>
    {
        set.SetIsOriginAllowed(origin => true)
           .AllowAnyHeader()
           .AllowAnyMethod()
           .AllowCredentials();
    });
});
相关文章
相关标签/搜索