vue netcore signalr写法

let endpoint = localStorage.server_url + "/chathub";
    let s = new signalR.HubConnectionBuilder()
      .withUrl(endpoint)
      .configureLogging(signalR.LogLevel.Error)
      .build();
    s.on("RefreshMessage", (data) => {
      console.log(data);
      this.executeQueryPage();
    });
    s.on("NoticeMessage", (data) => {
      console.log(data);
      this.NoticeMessage(data);
    });
    s.start();
public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers().AddNewtonsoftJson();
            
            services.AddSignalR().AddJsonProtocol();
        }

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, Microsoft.AspNetCore.Hosting.IApplicationLifetime lifetime)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }            
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapHub<ChatHub>("/ChatHub");
            });
        }

public class ChatHub : Hub
    {
       
    }

public class CustomController : ControllerBase
    {
        private readonly IHubContext<ChatHub> _hub;
        public CustomController(IHubContext<ChatHub> hub)
        {
            _hub = hub;
        }
        [HttpGet]
        public ActionResult<object> RefreshMessage(string info)
        {
            _hub.Clients.All.SendAsync("RefreshMessage", info);
            return "ok";
        }
        [HttpGet]
        public ActionResult<object> NoticeMessage(string info)
        {
            _hub.Clients.All.SendAsync("NoticeMessage", info);
            return "ok";
        }
    }

后端直接触发接口,即可往前端主动发送消息

posted @ 2021-09-17 11:17  天天的蓝色  阅读(144)  评论(0编辑  收藏  举报