netcore3.1 webapi使用signalR
前言
今天尝试了一下signalR,感觉还不错,因为暂时用不到,就写一篇博文来记录搭建过程,以免以后给忘了,基于官方文档写的,不过官方没有webapi调用例子,就自己写了一下,大神勿喷
使用
1.创建一个netcore3.1 webapi程序,nuget引用一下Microsoft.AspNetCore.SignalR,我这里是1.1.0版本

2.创建一个类 SignalRHub.cs 用来自定义集线器 继承自SignalR的集线器 代码如下
using Microsoft.AspNetCore.SignalR;
using System;
using System.Threading.Tasks;
namespace SignalR_Server{
public class SignalRHub:Hub {
public async Task sendall(string user, string message)
{
await Clients.All.SendAsync("toall",user,message,"给所有人发");
}
/// <summary>
/// 重写集线器连接事件
/// </summary>
/// <returns></returns>
public override Task OnConnectedAsync()
{
Console.WriteLine($"{Context.ConnectionId}已连接");
return base.OnConnectedAsync();
}
/// <summary>
/// 重写集线器关闭事件
/// </summary>
/// <param name="exception"></param>
/// <returns></returns>
public override Task OnDisconnectedAsync(Exception exception)
{
Console.WriteLine("触发了关闭事件");
return base.OnDisconnectedAsync(exception);
}
}}
3.修改Startup中的ConfigureServices方法 代码如下
public void ConfigureServices(IServiceCollection services)
{
//配置SignalR服务 配置跨域
services.AddCors(options => options.AddPolicy("CorsPolicy",
builder =>
{
builder.AllowAnyMethod()
.AllowAnyHeader()
.WithOrigins("http://localhost:51083")
.AllowCredentials();
}));
services.AddSignalR();
services.AddControllers(); }
4.修改Startup中的Configure方法 代码如下
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
//使用跨域
app.UseCors("CorsPolicy");
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
//使用集线器
endpoints.MapHub<SignalRHub>("/chatHub");
});
}
5.因为要实现前后端分离 这里我们再打开一个vs 创建一个mvc项目 用来模拟前端

将图片上的这三个文件里面的代码替换成我的 其中signalr.js是官方的 下载方式如下
(1)在“解决方案资源管理器” 中,右键单击项目,然后选择“添加” >“客户端库” 。
(2)在“添加客户端库” 对话框中,对于“提供程序” ,选择“unpkg” 。
(3)对于“库” ,输入 @microsoft/signalr@3,然后选择不是预览版的最新版本
(4)选择“选择特定文件” ,展开“dist/browser” 文件夹,然后选择“signalr.js” 和“signalr.min.js”
(5)将“目标位置” 设置为 wwwroot/js/ ,然后选择“安装”
该方法复制于弱水三千 只取一瓢饮
感谢老哥 大家也可以参考官方文档进行下载
剩下的两个文件代码很简单 我就不多说了
chat.js
"use strict";
var connection = new signalR.HubConnectionBuilder().withUrl("http://localhost:5000/chatHub").build();
//Disable send button until connection is establisheddocument.getElementById("sendButton").disabled = true;
//这个可以不一致
connection.on("toall", function (user, message,test)
{
var msg = message;
var encodedMsg = user + " says " + msg + "\n来源是" + test;
var li = document.createElement("li");
li.textContent = encodedMsg;
document.getElementById("messagesList").appendChild(li);});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("sendall", user, message).catch(function (err) {
return console.error(err.toString());
});
event.preventDefault();
});
Index.cshtml
@page<div class="container">
<div class="row"> </div>
<div class="row">
<div class="col-2">用户名</div>
<div class="col-4"><input type="text" id="userInput" /></div>
</div>
<div class="row">
<div class="col-2">要发送的消息</div>
<div class="col-4"><input type="text" id="messageInput" /></div>
</div>
<div class="row">
</div>
<div class="row">
<div class="col-6">
<input type="button" id="sendButton" value="发送消息" />
</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.js"></script><script src="~/js/chat.js"></script>
然后启动服务端和客户端 注意这里服务端我们使用kestrel的方式启动

启动成功可以看到控制台成功打印出了连接的用户id 测试发消息也正常

6.现在我们要通过api的方式进行请求了 在服务端新建一个控制器SignalRTestController 代码如下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Ladder.Data;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
namespace SignalR_Server.Controllers{
[Route("api/[controller]")]
[ApiController]
public class SignalRTestController : ControllerBase {
private readonly IHubContext<SignalRHub> _hubContext;
public SignalRTestController(IHubContext<SignalRHub> hubClients)
{
_hubContext = hubClients;
}
[HttpGet("index")]
public string index()
{
return "HELLO World";
}
[HttpGet("sendall")]
public void SendAll()
{
//给所有人推送消息
_hubContext.Clients.All.SendAsync("toall", "后端","你好","给所有人发");
}
[HttpGet("sendToUser")]
public void SendToUser(string user)
{
//给指定人推送消息
_hubContext.Clients.Client(user).SendAsync("toall", "后端", $"你好{user}", "只给你发");
}
}}
然后启动服务端和客户端 将客户端的页面打开两个
测试一下给指定人发

测试一个给所有人发

ok啦~
netcore3.1 webapi使用signalR的更多相关文章
- WebAPI集成SignalR
WebAPI提供通用数据接口,SignalR提供实时消息传输,两者可以根据实际业务需求进行组合. 环境 版本 操作系统 Windows 10 prefessional 编译器 Visual Studi ...
- asp.net core 2.0 webapi集成signalr
asp.net core 2.0 webapi集成signalr 在博客园也很多年了,一直未曾分享过什么东西,也没有写过博客,但自己也是汲取着博客园的知识成长的: 这两天想着不能这么无私,最近.N ...
- csc.rsp Nuget MVC/WebAPI、SignalR、Rx、Json、EntityFramework、OAuth、Spatial
# This file contains command-line options that the C# # command line compiler (CSC) will process as ...
- netcore3.0 webapi集成Swagger 5.0
在项目中引用Swashbuckle.AspNetCore和Swashbuckle.AspNetCore.Filters两个dll,在Startup中的ConfigureServices相关配置代码如下 ...
- netCore3.0+webapi到前端vue(前端)
前篇已经完成后端配置并获取到api连接 https://www.cnblogs.com/ouyangkai/p/11504279.html 前端项目用的是VS code编译器完成 vue 第一步 引入 ...
- netCore3.0+webapi到前端vue(后端)
第一步创建api项目 创建完成启动F5!! 如图 数据库我用的是mysql 用ef操作数据 开发环境:Win10 + VS2019Mysql服务器版本:8.0.16 1.下载并安装插件(必备) MyS ...
- netcore3.0 webapi集成Swagger 5.0,Swagger使用
Swagger使用 1.描述 Swagger 是一个规范和完整的框架,用于生成.描述.调用和可视化 RESTful 风格的 Web 服务. 作用: 1.接口的文档在线自动生成. 2.功能测试 本文转自 ...
- Asp.NetCore3.1 WebApi 使用Jwt 授权认证使用
1:导入NuGet包 Microsoft.AspNetCore.Authentication.JwtBearer 2:配置 jwt相关信息 3:在 startUp中 public void Confi ...
- Vue学习使用系列九【axiox全局默认配置以及结合Asp.NetCore3.1 WebApi 生成显示Base64的图形验证码】
1:前端code 1 <!DOCTYPE html> 2 <html lang="en"> 3 4 <head> 5 <meta char ...
随机推荐
- 高精地图技术专栏 | 基于空间连续性的异常3D点云修复技术
1.背景 1.1 高精资料采集 高精采集车是集成了测绘激光.高性能惯导.高分辨率相机等传感器为一体的移动测绘系统.高德高精团队经过多年深耕打造的采集车,具有精度高.速度快.数据产生周期短.自动化程度高 ...
- CentOS 7 卸载 OpenJDK 安装 OracleJDK
查看 JDK 安装版本 java -version java version 1.7.0_51 OpenJDK Runtime Environment ( rhel-2.4.5.5.el7-x86_6 ...
- c/c++ switch case内括号
如果在case语句中有定义变量,则必须要加{},否则会报错.
- 003-Java中的变量和数据类型
@ 目录 一.变量 1.什么变量 2.变量的三要素 3.变量的命名规范 4.变量的分类 5.变量的作用域 6.变量的注意事项 二.数据类型 1.什么是数据类型 2.数据类型有什么用 3.数据类型的分类 ...
- [Fundamental of Power Electronics]-PART II-8. 变换器传递函数-8.1 Bode图回顾
8.0 序 工程设计过程主要包括以下几个过程: 1.定义规格与其他设计目标 2.提出一个电路.这是一个创造性的过程,需要利用工程师的实际见识和经验. 3.对电路进行建模.变换器的功率级建模方法已经在第 ...
- Python基础(十六):文件读写,靠这一篇就够了!
文件读写的流程 类比windows中手动操作txt文档,说明python中如何操作txt文件? 什么是文件的内存对象(文件句柄)? 演示怎么读取文件 ① 演示如下 f = open(r"D: ...
- Dynamics CRM证书更换
Dynamics CRM产品一般有两种认证方式.第一种是基于声明的内部访问也就是无证书单纯用账号密码验证.第二种就是联合身份认证,需要安装网站证书. 对于联合身份认证的情况因为需要安装证书,而且证书是 ...
- git版本控制之维护旧仓库和往仓库里放货物
[git bash下 git clone git项目地址:输入这个命令 就会在你运行命令路径下创建一个文件夹,名字就是这个仓库的名字!!这样就完成了把一个别人的旧仓库克隆到自己本地仓库中进行管理维护和 ...
- OAuth2 Token 一定要放在请求头中吗?
Token 一定要放在请求头中吗? 答案肯定是否定的,本文将从源码的角度来分享一下 spring security oauth2 的解析过程,及其扩展点的应用场景. Token 解析过程说明 当我们使 ...
- Java执行groovy脚本的两种方式
记录Java执行groovy脚本的两种方式,简单粗暴: 一种是通过脚本引擎ScriptEngine提供的eval(String)方法执行脚本内容:一种是执行groovy脚本: 二者都通过Invocab ...