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

问题

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

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.

1203160-20190311163228599-154165396.png

原始代码:

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

原因

出现该问题的原因是由于 CORS 策略设置不正确造成的,原始设置我是允许所有 Origin 来源。但是由于 dotnetCore 2.2 的限制,无法使用 AllowAnyOrigin() + AllowCredentials() 的组合,只能显式指定 Origin 来源,或者通过下述方式来间接实现。

解决

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

在这里我们只需要将其设置为一直返回 true 即可。
最终代码如下:

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

转载于:https://www.cnblogs.com/myzony/p/10511492.html

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值