天天看點

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.
           
ASP.NET Core 使用 SignalR 遇到的 CORS 問題

原始代碼:

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