問題
將 signalr 集成到 asp.net core mvc 程序的時候,按照官方 demo 配置完成,但使用 demo 頁面建立連接一直提示如下信息。
1
|
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.
|
原始代碼:
1
2
3
4
5
6
7
8
9
10
|
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
即可。
最終代碼如下:
1
2
3
4
5
6
7
8
9
10
|
services.addcors(op =>
{
op.addpolicy(monitorstartupconsts.defaultcorspolicyname,
set
=>
{
set
.setisoriginallowed(origin =>
true
)
.allowanyheader()
.allowanymethod()
.allowcredentials();
});
});
|