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.

原始代碼:

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();
	});
});


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM