- program.cs 添加signalr、添加跨域,暂时允许所有跨域,use cors,添加signalr端点
builder.Services.AddSignalR();
builder.Services.AddCors(options =>
{
options.AddPolicy("cors",
builder => builder
.SetIsOriginAllowed(_=>true)
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod());
});
app.UseCors("cors");
app.UseEndpoints(endpoints => {
endpoints.MapHub<ChatHub>("/ChatHub");
});
- ChatHub 代码:将接收到的消息发送给其他所有客户端,这里需要添加跨域特性
[EnableCors("cors")]
public class ChatHub : Hub
{
[EnableCors("cors")]
public async Task guang_bo(string msg)
{
await Clients.AllExcept(this.Context.ConnectionId).SendAsync("guang_bo", this.Context.ConnectionId + "\t" + msg + " \n");
}
}
- 到这里,后端signalr添加、跨域、ChatHub已完成
- Vue代码添加 aspnet/signalr 库
- vue引入signalr
import * as signalR from "@aspnet/signalr";
- data中定义,mounted中signalr连接
data()
{
let isdebug = false;
if(isdebug)
{
url = "http://localhost:5189";
}
else
{
url = "http://www.xxx.cn:8088";
}
return {
base_url:url,
connection:"",
}
},
mounted(){
this.$data.connection = new signalR.HubConnectionBuilder()
.withUrl(`${this.$data.base_url}/ChatHub` ,
{
skipNegotiation: true,
transport: signalR.HttpTransportType.WebSockets
}
)
.configureLogging(signalR.LogLevel.Error).build();
this.$data.connection.start();
this.$data.connection.on("guang_bo", data => {
console.log(data);
this.$data.receiveMsg += data;
});
}
```
7. 关键步骤,nginx配置文件
```nginx
# 前端反向代理
server {
listen 80; # 前端端口
server_name qmtdlt.cn; # 前端域名
location / {
root html/dist; # 前端发布地址
index index.html index.htm; # index文件,默认
proxy_http_version 1.1; # signalr 配置必须
proxy_set_header Upgrade $http_upgrade; # signalr 配置必须
proxy_set_header Connection "upgrade"; # signalr 配置必须
}
location /api {
proxy_pass http://www.qmtdlt.cn:8088/api/; # 后端地址
}
}