I try use SignalR with .net core 3.1
, Its the first time i need to use it. I have no expirience with SignalR.
It seems like the same code working on .NET 5
, Unless im missing something
I tried understand why i get the error with no success. In my API endpoitns i dont have CORS errors I get the error:
Access to XMLHttpRequest at 'http://XXX:5421/managerhub/negotiate' from origin 'http://XXX:8080' 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.
My hub class:
[EnableCors("AnotherPolicy")]
public class TestHub : Hub
{
IHubContext<TestHub> _hubContext = null;
private static bool _firstTime = true;
public TestHub(IHubContext<TestHub> hubContext)
{
if (_firstTime)
{
_firstTime = false;
}
_hubContext = hubContext;
Task.Run(() => {
Thread.Sleep(10000);
Update(null,1);
});
}
[EnableCors("AnotherPolicy")]
public void Update(object sender, ushort participantId)
{
_hubContext.Clients.All.SendAsync("test", participantId);
}
}
My Services:
...
var corsBuilder = new CorsPolicyBuilder();
corsBuilder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
services.AddCors(opt => {
opt.AddPolicy("AnotherPolicy", corsBuilder.Build());
});
Configure:
...
app.UseCors("AnotherPolicy");
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapHub<TestHub>("/managerhub", options =>
{
}).RequireCors("AnotherPolicy");
});
And my client code:
import { HubConnectionBuilder, LogLevel } from "@aspnet/signalr";
const Url =
process.env.NODE_ENV === "development"
? "http://localhost:5421"
: location.origin;
const SignalR = (function () {
let status;
let _connected = false;
let _managerHub = new HubConnectionBuilder()
.withUrl(Url + `/managerhub`)
.configureLogging(LogLevel.Information)
.build();
let _retryTimerId;
let _registeredEvents = [];
function UpdateStatus(moreInfo = "") {
console.log(
"%c SignalR ",
"background: #148F77; color: white;",
`${status}${moreInfo ? "; " + moreInfo : ""}`
);
}
function StartConnection() {
if (_connected) return;
_managerHub
.start()
.then(() => {
_retryTimerId = undefined;
_connected = true;
status = "Connected";
UpdateStatus(`id: ${_managerHub.id}`);
})
.catch((e) => {
// console.error(e);
_connected = false;
status = "Disconnected";
UpdateStatus();
});
}
StartConnection();