[英]SignalR, ReactJs and Dotnet Core: CORS Issue
I am trying to implement SignalR in a Dotnet Core + ReachtJS web application.我正在尝试在 Dotnet Core + ReachtJS web 应用程序中实现 SignalR。 While calling the API and making a SignalR connection, I am facing a CORS issue.
在调用 API 并建立 SignalR 连接时,我遇到了 CORS 问题。
ReactJS SignalR Connection Code: ReactJS SignalR 连接代码:
useEffect(() => {
const newConnection = new HubConnectionBuilder()
.withUrl('https://myapi.com/hubs/signalrconn')
.withAutomaticReconnect()
.build();
setConnection(newConnection);
}, []);
Scenario 1: Below configuration works for a specific server.场景 1:以下配置适用于特定服务器。 I am able to make a SignalR connection.
我能够建立 SignalR 连接。 Below is my config code of API:
下面是我的 API 的配置代码:
services.AddCors(options =>
{
options.AddPolicy("prod",
builder => builder.WithOrigins("https://reactapp.com")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials());
});
app.UseCors("prod"); // This line is part of Configure method.
The issue with the above approach: This works only for a singal machine ie reactapp.com.上述方法的问题:这只适用于单机,即reactapp.com。 I would like to CORS enable for publicly.
我想公开启用 CORS。 So that I can deploy my react webapp on any webserver and it can access webapi.
这样我就可以在任何网络服务器上部署我的 react webapp 并且它可以访问 webapi。 So, I changed my CORS config:
所以,我改变了我的 CORS 配置:
services.AddCors(options => options.AddPolicy("AllowAll", builder =>
{
builder
.AllowAnyMethod()
.AllowAnyHeader()
.AllowAnyOrigin()
.AllowCredentials();
}));
But it will give me the below error.但它会给我以下错误。
How I can enable CORS for SignalR connection from any webserver?如何为来自任何网络服务器的 SignalR 连接启用 CORS?
EDIT : Below change in the react code, worked for me.编辑:下面的反应代码更改对我有用。
useEffect(() => {
const newConnection = new HubConnectionBuilder()
.withUrl('https://myapi.com/hubs/signalrconn', {
withCredentials: false
})
.withAutomaticReconnect()
.build();
setConnection(newConnection);
}, []);
You have a couple options.你有几个选择。
a.一个。 Configure all origins that you want to allow via
WithOrigins
通过
WithOrigins
配置您希望允许的所有来源
b.湾。 Set
withCredentials
to false on the javascript client https://docs.microsoft.com/aspnet/core/signalr/configuration?view=aspnetcore-5.0&tabs=javascript#configure-additional-options在
withCredentials
客户端https://docs.microsoft.com/aspnet/core/signalr/configuration?view=aspnetcore-5.0&tabs=javascript#configure-additional-options 上将 withCredentials设置为 false
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.