ABP调用SignalR

本文档详细记录了在ABP框架4.2版本中使用SignalR的全过程,包括安装Volo.Abp.AspNetCore.SignalR NuGet包,服务器端配置,集线器(Hub)设置,客户端配置及页面集成。通过创建ChatHub实现消息传递功能,并提供了客户端页面Chat.cshtml和Chat.js的代码示例,帮助读者理解ABP框架与SignalR的结合使用。
摘要由CSDN通过智能技术生成

简介

记录一下自己在学习ABP4.2框架中遇到的一些问题,这个是我看的官网上的例子中遇到的一些坑跟大家分享一下;ABP官网.

安装包

我安装的是Volo.Abp.AspNetCore.SignalR NuGet包

服务器端配置

配置文件中添加typeof(AbpAspNetCoreSignalRModule)

namespace SignalRDemo.Web
{
    [DependsOn(
        typeof(AbpAspNetCoreSignalRModule)
        )]
    public class SignalRDemoWebModule : AbpModule
    {

        public override void ConfigureServices(ServiceConfigurationContext context)
        {
            var hostingEnvironment = context.Services.GetHostingEnvironment();
            var configuration = context.Services.GetConfiguration();
			//根据官方的说法添加了typeof(AbpAspNetCoreSignalRModule)就不需要app.UseEndpoints(...)
			//也可以自己配置一写相关的东西
            //context.Services.AddTransient<ChatHub>();
            //Configure<AbpSignalROptions>(options =>
            //{
            //    options.Hubs.Add(
            //        new HubConfig(typeof(ChatHub),"/ChuatHub",hubOptions=> {
            //            hubOptions.LongPolling.PollTimeout = TimeSpan.FromSeconds(30);
            //        })
            //        );
            //});       
        }    
    }
}

集线器配置

集线器说白了就是服务器收发消息的一个服务中心;
在集线器里也是可以配置消息路由的[HubRoute("/chatHub")]

using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.SignalR;
using Volo.Abp.AspNetCore.SignalR;
using Volo.Abp.Identity;

namespace SignalRDemo.Web
{
    [Authorize]
    [HubRoute("/chatHub")]
    public class ChatHub : AbpHub
    {
        private readonly IIdentityUserRepository _identityUserRepository;
        private readonly ILookupNormalizer _lookupNormalizer;

        public ChatHub(IIdentityUserRepository identityUserRepository, ILookupNormalizer lookupNormalizer)
        {
            _identityUserRepository = identityUserRepository;
            _lookupNormalizer = lookupNormalizer;
        }

        public async Task SendMessage(string targetUserName, string message)
        {
            var username = CurrentUser.UserName;
            var targetUser = await _identityUserRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName(targetUserName));            
            message = $"{CurrentUser.UserName}: {message}";
            await Clients
                .User(targetUser.Id.ToString())
                .SendAsync("ReceiveMessage", message);
                //广播模式的
                //await Clients.All.SendAsync("ReceiveMessage", message);
        }
    }
}

客户端配置

官网上都是用命令行来添加包的,遇到了不少坑,就是环境安装问题;官网例子里用的是yarn安装然后用gulp迁移的;
首先VS里需要安装Node.js,因为里面带npm;然后在npm环境里执行下面的代码

npm install -g yarn
npm install gulp -g

然后就可以按照官网上的说明来执行命令了

yarn add @abp/signalr

gulp

执行完后wwwroot里就会有一个signalr的文件夹

客户端页面

Chat.cshtml

@page
@using Volo.Abp.AspNetCore.Mvc.UI.Packages.SignalR
@model SignalRDemo.Web.Pages.ChatModel
@section styles {
    <abp-style src="/Pages/Chat.css" />
}
@section scripts {
    <abp-script type="typeof(SignalRBrowserScriptContributor)" />
    <abp-script src="/Pages/Chat.js" />
}
<h1>Chat</h1>

<div>
    <abp-row>
        <abp-column size-md="_6">
            <div>All Messages:</div>
            <ul id="MessageList" style="">
            </ul>
        </abp-column>
        <abp-column size-md="_6">
            <form>
                <abp-row>
                    <abp-column>
                        <label for="TargetUser">Target user:</label>
                        <input type="text" id="TargetUser" />
                    </abp-column>
                </abp-row>
                <abp-row class="mt-2">
                    <abp-column>
                        <label for="Message">Message:</label>
                        <textarea id="Message" rows="4"></textarea>
                    </abp-column>
                </abp-row>
                <abp-row class="mt-2">
                    <abp-column>
                        <abp-button type="submit" id="SendMessageButton" button-type="Primary" size="Block" text="SEND!" />
                    </abp-column>
                </abp-row>
            </form>
        </abp-column>
    </abp-row>

</div>

Chat.js

$(function() {
    var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();

    connection.on("ReceiveMessage", function (message) {
        $('#MessageList').append('<li><strong><i class="fas fa-long-arrow-alt-right"></i>接收: ' + message + '</strong></li>');
    });
    connection.start().then(function () {
        console.log("开启");
    }).catch(function (err) {
        return console.error(err.toString());
    });
    
    $('#SendMessageButton').click(function(e) {
        e.preventDefault();

        var targetUserName = $('#TargetUser').val();
        var message = $('#Message').val();
        $('#Message').val('');

        connection.invoke("SendMessage", targetUserName, message)
            .then(function() {
                $('#MessageList')
                    .append('<li><i class="fas fa-long-arrow-alt-left"></i> 发送:' + abp.currentUser.userName + ': ' + message + '</li>');
            })
            .catch(function(err) {
                return console.error(err.toString());
            });
    });
});

结语

可喜可贺,可口可乐。现在可以愉快的和自己聊天了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值