摘要

在一个后台管理的页面想实时监控一些操作的数据,想到用signalR。

一个例子

asp.net core+signalR

使用Nuget安装包:Microsoft.AspNetCore.SignalR

在StartUp中启用signalR

  // This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
//services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddCors(options => options.AddPolicy("CorsPolicy",
builder =>
{
builder.AllowAnyMethod().AllowAnyHeader()
.WithOrigins("http://localhost:55830")
.AllowCredentials();
})); services.AddSignalR();
}
    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
} app.UseCors("CorsPolicy");
app.UseSignalR(routes =>
{
routes.MapHub<NotificationHub>("/notifyHub");
}); app.UseStaticFiles(); app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}/{w?}");
});
}
 public class NotificationHub:Hub
{
}

在api中,通过构造函数注入

 //[Produces("application/json")]
[Route("api/Mail")]
public class MailController : Controller
{ private IHubContext<NotificationHub> _hubContext;
public MailController(
IHubContext<NotificationHub> hubContext)
{
_mSMailUtil = mSMailUtil;
_requestHelper = requestHelper;
_webLogUtil = webLogUtil;
_accessor = accessor;
_hubContext = hubContext;
} [HttpGet("send")]
public IActionResult Send()
{
_hubContext.Clients.All.SendAsync("Notify", $" {DateTime.Now}:->{new Random().Next(1, 10000)}");
return this.Ok();
} }

客户端

需要引入signalr.js

// The following sample code uses modern ECMAScript 6 features
// that aren't supported in Internet Explorer 11.
// To convert the sample for environments that do not support ECMAScript 6,
// such as Internet Explorer 11, use a transpiler such as
// Babel at http://babeljs.io/.
//
// See Es5-chat.js for a Babel transpiled version of the following code: const connection = new signalR.HubConnectionBuilder()
.withUrl("/notifyHub")
.build(); connection.on("Notify", (message) => {
console.log(message);
const li = document.createElement("li");
li.style.color = "white";
const txt = "->" + message;
li.textContent = txt;
document.getElementById("ulList").appendChild(li); }); connection.start().catch(err => console.error(err.toString()));
<div style="margin-top:20px;">
<button id="btnAll" class="btn-danger">全部订阅</button>
</div>
<div style="background-color:black;width:100%;height:auto;margin-top:10px;">
<ul id="ulList" style="list-style-type:none;">
<li style="color:white;"> </li>
</ul>
</div>
<script src="~/lib/signalr/signalr.js"></script>
<script src="~/js/chat.js"></script>

测试

通过访问api/mail/send

在页面https://localhost:44362/Home/all可以看到通知结果

[asp.net core]SignalR一个例子的更多相关文章

  1. ASP.NET Core SignalR中的流式传输

    什么是流式传输? 流式传输是这一种以稳定持续流的形式传输数据的技术. 流式传输的使用场景 有些场景中,服务器返回的数据量较大,等待时间较长,客户端不得不等待服务器返回所有数据后,再进行相应的操作.这时 ...

  2. Asp.Net Core SignalR 与微信小程序交互笔记

    什么是Asp.Net Core SignalR Asp.Net Core SignalR 是微软开发的一套基于Asp.Net Core的与Web进行实时交互的类库,它使我们的应用能够实时的把数据推送给 ...

  3. Asp.Net Core SignalR 用泛型Hub优雅的调用前端方法及传参

    继续学习 最近一直在使用Asp.Net Core SignalR(下面成SignalR Core)为小程序提供websocket支持,前端时间也发了一个学习笔记,在使用过程中稍微看了下它的源码,不得不 ...

  4. ASP.NET Core SignalR

    ASP.NET Core SignalR 是微软开发的一套基于ASP.NET Core的与Web进行实时交互的类库,它使我们的应用能够实时的把数据推送给Web客户端. 功能 自动管理连接 允许同时广播 ...

  5. ASP.NET Core SignalR:基础概述

    一.简介 ASP.NET Core SignalR 是一个开源代码库,它简化了向应用添加实时 Web 功能的过程. 实时 Web 功能使服务器端代码能够即时将内容推送到客户端. SignalR 的适用 ...

  6. 使用websocket连接(对接)asp.net core signalr

    使用通用websocket连接asp.net core signalr 一.背景介绍 signalr的功能很强大,可以为我们实现websocket服务端节省不少的时间.但是可能由于不同的环境,我们在对 ...

  7. ASP.NET CORE使用WebUploader对大文件分片上传,并通过ASP.NET CORE SignalR实时反馈后台处理进度给前端展示

    本次,我们来实现一个单个大文件上传,并且把后台对上传文件的处理进度通过ASP.NET CORE SignalR反馈给前端展示,比如上传一个大的zip压缩包文件,后台进行解压缩,并且对压缩包中的文件进行 ...

  8. 给 asp.net core 写一个简单的健康检查

    给 asp.net core 写一个简单的健康检查 Intro 健康检查可以帮助我们知道应用的当前状态是不是处于良好状态,现在无论是 docker 还是 k8s 还是现在大多数的服务注册发现大多都提供 ...

  9. Serilog 是 ASP.NET Core 的一个插件,可以简化日志记录

    [翻译] ASP.NET Core 利用 Docker.ElasticSearch.Kibana 来记录日志 原文: Logging with ElasticSearch, Kibana, ASP.N ...

随机推荐

  1. linux脚本实现scp命令自动输入密码和yes/no等确认信息

    实现方式: 通过expect工具实现 #!/bin/bash yum -y install expect expect -c " spawn scp -r root@192.168.10.1 ...

  2. net core体系-web应用程序-4net core2.0大白话带你入门-1目录

    asp.net core2.0大白话带你入门 本系列包括: 1.新建asp.net core项目2.web项目目录解读3.配置访问地址4.环境变量详解5.配置文件6.日志7.DI容器8.服务的生命周期 ...

  3. 去掉select的原有样式

    1:设置select的边框为0px,背景设成透明(background: transparent;),这时候你会看到边框没有了,但是小三角还是在的.再在select外面加个div,固定死div的宽度, ...

  4. python面试题之Python是如何进行内存管理的

    python内部使用引用计数,来保持追踪内存中的对象,Python内部记录了对象有多少个引用,即引用计数,当对象被创建时就创建了一个引用计数,当对象不再需要时,这个对象的引用计数为0时,它被垃圾回收. ...

  5. HashMap实现原理简析及实现的demo(一看就明白)

    HashMap底层就是一个数组结构,数组中的每一项又是一个链表. jdk源码: transient Node<K,V>[] table; static class Node<K,V& ...

  6. excel表格导入数据库数据存在则更新不存在添加

    public void excelToDB() throws ParseException { String datapath = this.getParameter("datapath&q ...

  7. 爬虫之 案列1补充(pipelines优化)

    1. 先打开settings.py文件将 'ITEM_PIPELINES'启动(取消注释即可) 2. spider代码 # -*- coding: utf-8 -*- import scrapy im ...

  8. Linux常用命令行补充——持续更新

    1.查看文件夹大小 =>ls -lht 路径 ls -lht /opt/jars 2.查看文件大小 =>du -sh / du -sh /opt/jars/calllog.csv 3.编辑 ...

  9. Java大数相加(多个大数相加)-hdu1250

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1250 题目描述: 题目大意是:已知一个Hat's Fibonacci序列,该序列满足F(1) = 1, ...

  10. 版本控制系统-SVN(1)

    1.   SVN介绍 1.1.  简介 SVN(subversion),版本管理工具,与CVS一样,SVN是一个可跨平台的开源版本控制系统,Subversion管理随时间变化的数据.这些数据都被放置在 ...