SignalR《二》接着前篇的继续
SignalR《二》接着前篇的继续
SignalR身份验证
在ChatRoomHub加上[Authorize] 这样登录了才能发送消息
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.SignalR;
using SignalRStudy.Entity;
using System.Security.Claims;
namespace SignalRStudy.Hubs
{
[Authorize]
public class ChatRoomHub : Hub
{
private readonly UserManager<MyUser> _userManager;
public ChatRoomHub(UserManager<MyUser> userManager)
{
_userManager = userManager;
}
//SignalR的基本使用
public Task SendPublicMessage(string messgae)
{
//获取当前连接id
var connid = this.Context.ConnectionId;
var msg = $"{connid}:{DateTime.Now}发送了{messgae}";
//SendAsync 是对SendCoreAsync的封装
//对所有人发送消息 只有一个异步方法可以 不屑async 和 await
//ReceivePublicMessage 为前端接受消息方法
var res = Clients.All.SendAsync("ReceivePublicMessage", msg);
return res;
}
public async Task<string> SendPrivateMessage(string destUserName, string message)
{
var destUser = await _userManager.FindByNameAsync(destUserName);
if (destUser == null)
{
return "DestUserNotFound";
}
string destUserId = destUser.Id.ToString();
string srcUserName = this.Context.User!.FindFirst(ClaimTypes.Name)!.Value;
string time = DateTime.Now.ToShortTimeString();
await this.Clients.User(destUserId).SendAsync("ReceivePrivateMessage",
srcUserName, time, message);
return "ok";
}
}
}
如下图
前端代码(前端 Vue3 我不是很熟,不多讲了)
<template>
<fieldset>
<legend>登录</legend>
<div>
用户名:<input type="text" v-model="state.loginData.userName"/>
</div>
<div>
密码:<input type="password" v-model="state.loginData.password">
</div>
<div>
<input type="button" value="登录" v-on:click="loginClick"/>
</div>
</fieldset>
公屏:<input type="text" v-model="state.userMessage" v-on:keypress="txtMsgOnkeypress" />
<div>
私聊给<input type="text" v-model="state.privateMsg.destUserName"/>
说<input type="text" v-model="state.privateMsg.message"
v-on:keypress="txtPrivateMsgOnkeypress"/>
</div>
<div>
<ul>
<li v-for="(msg,index) in state.messages" :key="index">