摘要

在一个后台管理的页面想实时监控一些操作的数据,想到用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. JVM性能参数优化

    以上是jdk1.7的默认GC回收器 Java的gc回收的类型主要有几种 UseSerialGC, UseConcMarkSweepGC, UseParNewGC, UseParallelGC, Use ...

  2. nginx配置2

    第四节 nginx 配置文件 1 keepalive_timeout   65;  设定保存长久连接时长 0代表禁止, 若不设置默认是75s 2keepalive_requests   nu;  在一 ...

  3. Codeforces 803G Periodic RMQ Problem 线段树

    Periodic RMQ Problem 动态开点线段树直接搞, 我把它分成两部分, 一部分是原来树上的, 一部分是后来染上去的,两个部分取最小值. 感觉有点难写.. #include<bits ...

  4. Codeforces 420D Cup Trick 平衡树

    Cup Trick 平衡树维护一下位置. #include<bits/stdc++.h> #include <bits/extc++.h> #define LL long lo ...

  5. fillder--信息面板显示请求耗时列

    class Handlers--------->Ctrl+R,找到该方法,加上以下方法即可 { // 显示每行请求的发起时间:时分秒毫秒 public static BindUIColumn(& ...

  6. Nginx的配置与部署研究,Upstream负载均衡模块

    Nginx 的 HttpUpstreamModule 提供对后端(backend)服务器的简单负载均衡.一个最简单的 upstream 写法如下: upstream backend { server ...

  7. BZOJ4556 [Tjoi2016&Heoi2016]字符串 SA ST表 二分答案 主席树

    原文链接https://www.cnblogs.com/zhouzhendong/p/BZOJ4556.html 题目传送门 - BZOJ4556 题意 给定一个长度为 $n$ 的字符串 $s$ . ...

  8. web.xml中使用web前缀配置无法访问controller

    <web:context-param> <web:param-name>contextConfigLocation</web:param-name> <web ...

  9. webpack的build的时候时间长处理方案

    观察第一次build的时间比较长,之后的编译时间较短,可以通过webpack -watch 监测性能 1, 将webpack升级到4.0,build 的速度提升很多 2,用webpack -watch ...

  10. ACM-ICPC Beijing 2016 Genius ACM(倍增+二分)

    描述 给定一个整数 M,对于任意一个整数集合 S,定义“校验值”如下: 从集合 S 中取出 M 对数(即 2∗M 个数,不能重复使用集合中的数,如果 S 中的整 数不够 M 对,则取到不能取为止),使 ...