使用SignalR asp.net core通信 (一)

使用SignalR进行通信

服务端使用Asp.Net Core 3.1 客户端使用 Vue


服务端配置

配置SignlaR

SignalR中间件需要一些服务,这些服务通过调用配置 services.AddSignalR

public void ConfigureServices(IServiceCollection services)
{
    services.AddSignalR();//添加SignalR服务
    services.AddRazorPages();
    //设置跨域问题  因为前后端分离可能不在统一站点部署,会出现跨域问题,这里进行跨域配置
     services.AddCors(options => {
            options.AddPolicy("SignalRCors", policy => policy.AllowAnyOrigin()
                .AllowAnyHeader()
                .AllowAnyMethod()
                .AllowCredentials());
    });
    services.AddMvc(o=>o.EnableEndpointRouting = false);
}

向 SignalR ASP.NET Core 应用程序添加功能时, SignalR 通过 endpoint.MapHubStartup.Configure 方法的回调中调用来设置路由 app.UseEndpoints

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");
    }

    app.UseStaticFiles();
    //使用配置的跨域策略
    app.UseCors("SignalRCors");
    app.UseRouting();

    app.UseAuthorization();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapRazorPages();
        endpoints.MapHub<ChatHub>("/chathub");//这里配置SignalR路由
    });
    app.UseMvc();
}

使用SignalR

通过声明从继承的类 Hub ,并向其添加公共方法来创建中心。
创建文件夹名为 Hubs

public class ChatHub : Hub
{
    public Task SendMessage(string user, string message)
    {
        return Clients.All.SendAsync("ReceiveMessage", user, message);
    }
}

可以指定返回类型和参数(包括复杂类型和数组),就像在任何 c # 方法中一样。 SignalR处理参数和返回值中的复杂对象和数组的序列化和反序列化。


客户端 在vue中使用

安装对应的signalR插件

npm i --save @aspnet/signalr

创建连接

封装js,这里是在utils文件夹下创建了signalR.js文件,内容如下

//引入安装的signalr包
import * as signalR from '@aspnet/signalr'
const signal = new signalR.HubConnectionBuilder()
    .withUrl('http://localhost:52970/chathub')//服务器地址
    .build()
export default {
    install: function(Vue) {
        Vue.prototype.signalr = signal
    }
}

 然后在main.js中全局引入

import signalr from './utils/signalR'
Vue.use(signalr)

在任意组件中使用

mounted () {
    this.signalr.start().then(() => {
        console.log('连接成功');
    })
},
methods () {
    CreateOn(){
        //ReceiveMessage和Clients.All.SendAsync中的第一个参数对应
        this.signalr.on('ReceiveMessage',res=>{
            //可以写业务逻辑
            //res 返回的是后台传过来的数据
            console.log(res);
        })
    },
    SendMessage(){
        var user = "123";
        var message = "123";
        //SendMessage和后台方法对应
        this.signalr.invoke("SendMessage", user, message).catch(function (err) {
            console.error(err.toString());
        });
    }
}

文档资源

原文地址:https://www.cnblogs.com/qs315/p/13323768.html