I made a simple SignalR implementation following This Video. I added its dependency with builder.Services.AddSignalR();
in my Program.cs
class. Then added Map into my CustomHub with this : app.MapHub<PublicChatHub>("public-chat");
Here My Hub Class
using Microsoft.AspNetCore.SignalR;
namespace WebAPI.SignalR;
public sealed class PublicChatHub : Hub
{
public override async Task OnConnectedAsync()
{
await Clients.All.SendAsync("ReceiveMessage", $"{Context.ConnectionId} connected.");
}
public async Task SendMessage(string message)
{
await Clients.All.SendAsync("ReceiveMessage", message);
}
public override async Task OnDisconnectedAsync(Exception? exception)
{
await Clients.All.SendAsync("ReceiveMessage", $"{Context.ConnectionId} disconnected.");
}
}
When i try to call wss://localhost:7142/public-chat
via postman connecting socket successfully but code not hitting my breakpoint on OnConnectedAsync()
.
Sending this message after connect :
{
"protocol": "json,
"version": 1
}�
� is 0x1E ascii.
For my main question, which i cannot access my hub via postman
with web socket, i figured out my � is not actually 0x1E ascii or something like it. On this link i found a body template which similiar to mine, but the end character is different.
Changed my message body with this:
{"protocol":"json","version":1}
(should be escape character at end, cannot post it but you can find on link at top)
and my wss://localhost:7142/public-chat
started response.
Thanks to fatih, helped to solve my js client, running with Live Server
vscode extension problem to solve, which was CORS.
Solved it with use app.Cors();
middleware as Services, which is
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowAll",
configure => configure.WithOrigins("http://localhost:5500") // your client
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials()
);
});
and use policy as middleware:
app.UseCors("AllowAll");
app.MapHub<PublicChatHub>("/public-chat");
For js client which running with Live Server
extension my codes are :
let connection = new signalR.HubConnectionBuilder()
.withUrl("https://localhost:7142/public-chat") // your server (check out http or https request)
.configureLogging(signalR.LogLevel.Information)
.build();
connection.start().then(function () {
console.log("connected");
}).catch(function (err) {
return console.error(err.toString());
});
connection.on("ReceiveMessage", function (message) {
console.log("Message received: " + message);
});
And calling it with simple html page.
<head>
<script src="https://unpkg.com/@microsoft/signalr@latest/dist/browser/signalr.min.js"></script>
</head>
<body>
<script src="index.js"></script>
</body>
After all, both my client; postmand and js run success.