参考
.NET+Vue 使用SignalR推送数据 - netlock - 博客园 (cnblogs.com)
ASP.NET Core 使用 SignalR 遇到的 CORS 问题 - MyZony - 博客园 (cnblogs.com)
环境配置
后端
安装依赖包
Swashbuckle.AspNetCore
创建连接类
csharp
using Microsoft.AspNetCore.SignalR;
namespace SignalR
{
public class MyHub:Hub
{
public Task SendPublicMsg(string msg)
{
string connectionId = this.Context.ConnectionId;
string msgToSend = $"{connectionId} {DateTime.Now}:{msg}";
return Clients.All.SendAsync("PublicMsgReceived", msgToSend);
}
}
}
服务注册
ini
builder.Services.AddSignalR();
.........................
app.MapHub<MyHub>("/MyHub");
配置跨域
ini
// 添加跨域策略
string[] urls = new[] { "http://localhost:5173"};
builder.Services.AddCors(option =>
{
option.AddPolicy("CorsPolicy",
opt => opt
.WithOrigins(urls)
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials());
});
.........................
// 使用跨域策略
app.UseCors("CorsPolicy");
前端
安装依赖
npm install @microsoft/signalr
核心代码
修改HelloWorld.vue
xml
<script setup>
import { onMounted,ref } from 'vue';
import * as signalR from "@microsoft/signalr"
let input_value = ref()
let connc = ref()
const connection = new signalR.HubConnectionBuilder()
.withUrl("https://localhost:7253/MyHub")
.withAutomaticReconnect() //断线自动重连
.build();
connection.start();
const fromResponse = ref([])
connection.on('PublicMsgReceived',msg=>{
console.log(msg)
fromResponse.value.push(msg)
})
//自动重连成功后的处理
connection.onreconnected(connectionId => {
alert(connectionId);
});
const submit = ()=>{
console.log(input_value.value)
connection.invoke("SendPublicMsg",input_value.value)
}
</script>
<template>
<input v-model="input_value">
<button style="border: 1px solid #ccc;" @click="submit">提交</button>
<ul>
<li v-for="(value, key, index) in fromResponse" :key="key" style="text-align : left;">{{ key + 1 }}: {{ value }}</li>
</ul>
</template>
<style scoped>
</style>
注意参数要与后端对应
测试
分别打开两个浏览器窗口,可以进行即时通讯