將 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 源,若是驗證經過則返回 true
。requests
在這裏咱們只須要將其設置爲一直返回 true
便可。
最終代碼以下:string
services.AddCors(op => { op.AddPolicy(MonitorStartupConsts.DefaultCorsPolicyName, set => { set.SetIsOriginAllowed(origin => true) .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); }); });