ASP.NET Core+Vue3 implements SignalR communication
Starting from ASP.NET Core version 3.0, SignalR’s Hub has been integrated into the ASP.NET Core framework. Therefore, in later versions of ASP.NET Core, it is no longer necessary to reference the Microsoft.AspNetCore.SignalR package separately to use the Hub.
Create a class in the project that inherits Hub,
The first is to write a CreateConnection method
ConnectionId is the unique identifier of the client connection identified in SignalR,
Associate userId with ConnectionId, so that you can send messages to a specific user or users.
SendMessageToUser method is used to send messages to specific users. It accepts two parameters: userId represents the user ID to be used to receive messages, and message represents the content of the message to be sent.
The main function of this method is to obtain the ConnectionId associated with the userId from the memory cache (IMemoryCache), then use the Clients.Client(connectionId.ToString()) method to find the corresponding client connection, and send the message to this user. This way, users can receive specific messages.
public class MyHub : Hub
{
private readonly IMemoryCache memoryCache;
public MyHub(IMemoryCache memoryCache)
{
this.memoryCache = memoryCache;
}
public void CreateConnection(int userId)
{
//Associate the user ID with the ConnectionId
memoryCache.Set(userId, Context.ConnectionId);
}
public async Task SendMessageToUser(int userId, string message)
{
if (memoryCache.TryGetValue(userId, out var connectionId))
{
await Clients.Client(connectionId.ToString()).SendAsync("ReceiveMessage", message);
}
}
}
Register hub in program file
//Register signalr
builder.Services.AddSignalR();
//Register hub The path here is the path of my Hub class in the project
app.MapHub("/SignalR/MyHub");
—————————————————————————————————————————————— ————————————————————————
Let the back-end and front-end download the @microsoft/signalr package in the vue project
npm i @microsoft/signalr --save
Create a myHub.js file
import * as signalr from '@microsoft/signalr';
const conn = new signalr.HubConnectionBuilder()
.withUrl('http://localhost:5124/SignalR/Myhub')
.withAutomaticReconnect()
.build();
export default conn;
.withUrl(‘http://localhost:5124/SignalR/Myhub’) The path here must be the same as app.MapHub(“/Signalr/Myhub”); configured in the Program in the api project .
withAutomaticReconnect() is used to enable automatic reconnection. This means that if the connection is lost, SignalR will automatically try to re-establish the connection to ensure real-time communication is maintained.
The .build() method builds and returns a SignalR connection object.
conn.start();Start establishing a connection with SignarlR.
—————————————————————————————————————————— ——————————————————————————
If so, here is a simple simulation of database login
API part
[Route("api/[controller]/[action]"), ApiController]
public class TestController : ControllerBase
{
List userList = new List()
{
new SysUser(1,"Wang Hedi","123456"),
new SysUser(2,"Wu Lei","123456"),
new SysUser(3,"Zhao Lusi","123456")
};
[HttpPost]
public ActionResult Login(SysUser sysUser)
{
var user = userList.Where(s => s.userName == sysUser.userName && s.userPwd == sysUser.userPwd).FirstOrDefault();
if (user is not null)
{
return Ok(user.userId);
}
return Ok("Failure");
}
}
public record SysUser(int? userId,string userName,string userPwd);
Vue part
import {ref,reactive,onMounted} from 'vue';
import axios from 'axios';
import myHub from './httpTools/myHub'; //Import hub
const loginUser=reactive({
userName:'Wang Hedi',
userPwd:'123456',
});
const loginBtn= ()=>{
axios.post('http://localhost:5159/api/test/login',loginUser)
.then(async res => {
console.log(res);
alert('success');
//Here, after successful login, the server's CreateConnection method in the MyHub class is called.
//Pass the userId returned after successful login
//Enable the client to establish a connection with the server
if(myHub.state.toString()!="Connected"){
await myHub.start();
}
myHub.invoke("CreateConnection",res.data);
})
}
//�ReceiveMessage here is used to accept messages sent by the server
//This ReceiveMessage name is defined by yourself
onMounted(() => {
myHub.on('ReceiveMessage', (message) => {
console.log("Message received by MyHub: "+message);
alert(message);
})
})
const message=ref();
const sendUserId=ref();
const sendMessage=()=>{
myHub.invoke("SendMessageToUser",Number(sendUserId.value),message.value)
}
Wang Hedi
Wu Lei
Zhao Lusi