111
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.SignalR;
|
||||
|
||||
namespace Application.Web.Controllers.Login
|
||||
{
|
||||
@@ -11,7 +12,11 @@ namespace Application.Web.Controllers.Login
|
||||
[ApiController]
|
||||
public class LoginController : ControllerBase
|
||||
{
|
||||
|
||||
private readonly IHubContext<ChatHub> _hubContext;
|
||||
public LoginController(IHubContext<ChatHub> hubContext)
|
||||
{
|
||||
_hubContext = hubContext;
|
||||
}
|
||||
/// <summary>
|
||||
/// 登录接口
|
||||
/// </summary>
|
||||
@@ -26,6 +31,7 @@ namespace Application.Web.Controllers.Login
|
||||
[HttpGet]
|
||||
public async Task<IPoAction> Test(string name)
|
||||
{
|
||||
await _hubContext.Clients.All.SendAsync("ReceiveMessage", "系统");
|
||||
return PoAction.Ok(name);
|
||||
|
||||
}
|
||||
|
||||
26
Service/Application.Web/Plug/ChatHub/ChatHub.cs
Normal file
26
Service/Application.Web/Plug/ChatHub/ChatHub.cs
Normal file
@@ -0,0 +1,26 @@
|
||||
using Microsoft.AspNetCore.SignalR;
|
||||
namespace Application.Web
|
||||
{
|
||||
public class ChatHub:Hub
|
||||
{
|
||||
// 客户端调用:发送消息给所有人
|
||||
public async Task SendMessage(string user, string message)
|
||||
{
|
||||
// 推送给所有客户端(Clients.All)
|
||||
await Clients.All.SendAsync("ReceiveMessage", user, message);
|
||||
}
|
||||
|
||||
// 可选:连接/断开事件
|
||||
public override async Task OnConnectedAsync()
|
||||
{
|
||||
await Clients.All.SendAsync("UserConnected", Context.ConnectionId);
|
||||
await base.OnConnectedAsync();
|
||||
}
|
||||
|
||||
public override async Task OnDisconnectedAsync(Exception? exception)
|
||||
{
|
||||
await Clients.All.SendAsync("UserDisconnected", Context.ConnectionId);
|
||||
await base.OnDisconnectedAsync(exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -70,6 +70,8 @@ builder.Services.AddCors(options =>
|
||||
|
||||
#endregion 配置跨域处理,允许所有来源
|
||||
|
||||
builder.Services.AddSignalR();
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
app.Services.UseInject();//启用框架
|
||||
@@ -98,8 +100,9 @@ app.UseHttpsRedirection();
|
||||
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
app.MapControllers();
|
||||
app.MapHub<ChatHub>("/chatHub");
|
||||
|
||||
app.MapControllers();
|
||||
app.MapControllerRoute(
|
||||
name: "default",
|
||||
pattern: "{controller=Home}/{action=Index}/{id?}")
|
||||
|
||||
Reference in New Issue
Block a user