.net 5 使用Signalr入门

近期项目需要用到signalr,弄了个入门的简单前后端分离demo

 

文章介绍一下怎么用signalr实现一个简单的聊天室及后台推送

文章底部有资源地址及gitee地址,感兴趣的可以下载查看,文章能帮助到大家的话请给个赞

添加后台接口

新建一个.net 5 的asp .net core webapi项目

1.右键管理nuget程序包 安装Microsoft.AspNetCore.Signalr
2.在新建项目下添加hubs文件夹>文件夹新建 ChatHub.cs文件

using Microsoft.AspNetCore.SignalR;
using System;
using System.Threading.Tasks;

namespace SignalrWebApi.Hubs
{
    public class ChatHub : Hub
    {
        /// <summary>
        /// 接收前端消息,并发送给连接的全部用户
        /// </summary>
        /// <param name="user"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public async Task HandMessage(string user, string message)
        {
            //TO DO 可以加缓存,存储用户信息和对应的连接Id
            await Clients.All.SendAsync("ReceiveMessage", user, message);
        }

        /// <summary>
        /// 连接成功
        /// </summary>
        /// <returns></returns>
        public  override async Task OnConnectedAsync()
        {
            await Clients.All.SendAsync("ConnectMessage", Context.ConnectionId);
        }

        /// <summary>
        /// 退出连接
        /// </summary>
        /// <returns></returns>
        public override async Task OnDisconnectedAsync(Exception? exception)
        {
            //TO DO 可以从缓存,返回对应掉线用户,同时清除改用户缓存
            await Clients.All.SendAsync("ConnectMessage", Context.ConnectionId, exception?.Message);
        }        
    }
}

3.Startup.cs 配置

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using SignalrDemoApi.Hubs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace SignalrDemoApi
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {

            services.AddControllers();
            services.AddSignalR();   //添加SignalR
            //创建项目时勾选openapi支持会自动创建Swagger相关内容
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "SignalrDemoApi", Version = "v1" });
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "SignalrDemoApi v1"));
            }

            app.UseRouting();
 app.UseCors(option => option.WithOrigins("http://localhost:53649").AllowCredentials().AllowAnyMethod().AllowAnyHeader());  //配置跨域  http://localhost:53649是前端页面地址,注意launchSettings.json中指定
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapHub<ChatHub>("/chatHub");   //配置前端接口
            });
        }
    }
}

后台项目就配置好了

添加页面

1.页面signalr.js下载

创建ASP.NET Core Web 应用程序

在“解决方案资源管理器”中,右键单击项目,然后选择“添加”>“客户端库” 。

“提供程序”,选择“unpkg”>“库”,输入 @microsoft/signalr@latest

选择“选择特定文件”,展开“dist/browser”文件夹,然后选择“signalr.js”和“signalr.min.js”。

将“目标位置”设置为 wwwroot/js/signalr/,然后选择“安装”。

 2.页面及js

给项目Index.cshtml页面内容替换成

@page
<div class="container">
    <div class="row">&nbsp;</div>
    <div class="row">
        <div class="col-2">User</div>
        <div class="col-4"><input type="text" id="userInput" /></div>
    </div>
    <div class="row">
        <div class="col-2">Message</div>
        <div class="col-4"><input type="text" id="messageInput" /></div>
    </div>
    <div class="row">&nbsp;</div>
    <div class="row">
        <div class="col-6">
            <input type="button" id="sendButton" value="Send Message" />
        </div>
    </div>
</div>
<div class="row">
    <div class="col-12">
        <hr />
    </div>
</div>
<div class="row">
    <div class="col-6">
        <ul id="messagesList"></ul>
    </div>
</div>
<script src="~/js/signalr/dist/browser/signalr.js"></script>
<script src="~/js/chat.js"></script>

 在 wwwroot/js 文件夹中,创建 chat.js 文件 

"use strict";
//http://localhost:15931/chatHub是接口地址,自己注意配置
var connection = new signalR.HubConnectionBuilder().withUrl("http://localhost:15931/chatHub").build();

//Disable send button until connection is established
document.getElementById("sendButton").disabled = true;

connection.on("ReceiveMessage", function (user, message) {
    var li = document.createElement("li");
    document.getElementById("messagesList").appendChild(li);
    // We can assign user-supplied strings to an element's textContent because it
    // is not interpreted as markup. If you're assigning in any other way, you 
    // should be aware of possible script injection concerns.
    li.textContent = `${user} 发送消息 ${message}`;
});

connection.on("ConnectMessage", function (Id, message) {
    var li = document.createElement("li");
    document.getElementById("messagesList").appendChild(li);
    // We can assign user-supplied strings to an element's textContent because it
    // is not interpreted as markup. If you're assigning in any other way, you 
    // should be aware of possible script injection concerns.
    li.textContent = `连接标识 ${Id}  ${message}`;
});

connection.start().then(function () {
    document.getElementById("sendButton").disabled = false;
}).catch(function (err) {
    return console.error(err.toString());
});

document.getElementById("sendButton").addEventListener("click", function (event) {
    var user = document.getElementById("userInput").value;
    var message = document.getElementById("messageInput").value;
    connection.invoke("HandMessage", user, message).catch(function (err) {
        return console.error(err.toString());
    });
    event.preventDefault();
});

给两个项目都启动,就是一个简单的signalr前后端分离Demo了,具体详细大家可以参考微软官方文档或者下载代码自己调试修改

结语

官方文档地址 :https://docs.microsoft.com/zh-cn/aspnet/core/signalr/introduction?view=aspnetcore-5.0

gitee地址 https://gitee.com/gl125/signalr-demo

csdn资源下载 https://download.csdn.net/download/qq_36535245/20360402

.NET QQ技术交流群 681169497

  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值