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 ...
随机推荐
- 想了很久,一道Microsoft的笔试题目 —— Reversing Linked List
Reversing Linked List Given a constant K and a singly linked list L, you are supposed to reverse the ...
- A New Stone Game POJ - 1740
题目链接:https://vjudge.net/problem/POJ-1740#author=0 题意:有n堆石子,每次你可以选一堆拿走任意数量的石子,而且你还可以选择从这一堆剩下石子中取任意数量石 ...
- maven-plugin-shade 详解
一.介绍 [1] This plugin provides the capability to package the artifact in an uber-jar, including its d ...
- 力扣 - 剑指 Offer 09. 用两个栈实现队列
目录 题目 思路 代码 复杂度分析 题目 剑指 Offer 09. 用两个栈实现队列 思路 刚开始想的是用stack1作为数据存储的地方,stack2用来作为辅助栈,如果添加元素直接push入stac ...
- Hashtable 渐渐被人们遗忘了,只有面试官还记得,感动
尽人事,听天命.博主东南大学硕士在读,热爱健身和篮球,乐于分享技术相关的所见所得,关注公众号 @ 飞天小牛肉,第一时间获取文章更新,成长的路上我们一起进步 本文已收录于 「CS-Wiki」Gitee ...
- 网关Ocelot功能演示安排的明明白白~~~
前言 网关(Gateway)在微服务架构中至关重要,可以将其理解为是外部客户端(前端.MVC后台等调用方)与后台服务的连接点,通过这层可以做统一的处理,比如路由.身份认证和授权.服务治理等: 网关的好 ...
- KeyError:‘uid' Python常见错误
使用不存在的字典键值 检查字典和要查的内容 如有不正确改正即可
- CodeForces CF875C题解
题解 非常有意思的\(2-SAT\)的题. 听学长讲完之后感觉确实容易想到\(2-SAT\),顺理成章. 显然,对于两个串,对咱们来说有意义的显然是两个串中第一个不同的数字.那么,我们假设两个串分别是 ...
- vue 快速入门 系列 —— vue 的基础应用(上)
其他章节请看: vue 快速入门 系列 vue 的基础应用(上) Tip: vue 的基础应用分上下两篇,上篇是基础,下篇是应用. 在初步认识 vue一文中,我们已经写了一个 vue 的 hello- ...
- Ansible 教程
[注]本文译自:https://www.edureka.co/blog/ansible-tutorial/ 在阅读本文之前,你应该已经知道,Ansible 构成了 DevOps 认证的关键部分,它 ...