[asp.net core]SignalR一个例子

摘要

在一个后台管理的页面想实时监控一些操作的数据,想到用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可以看到通知结果

 

posted @   wolfy  阅读(1222)  评论(3编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
历史上的今天:
2016-06-22 [MongoDB]对数组操作
2015-06-22 [工具类]泛型集合转换为DataTable
点击右上角即可分享
微信分享提示