[asp.net core]SignalR一个例子

本文介绍如何在ASP.NET Core应用中使用SignalR实现实时数据推送。通过配置SignalR服务及创建Hub类,结合MailController控制器实现消息发送。客户端通过JavaScript连接Hub并接收消息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

摘要

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

 

转载于:https://www.cnblogs.com/wolf-sun/p/9213080.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值