我如何使用asp.netcore中的signalR核心向特定用户发送消息

时间:2019-06-16 11:57:54

标签: asp.net-core signalr asp.net-core-signalr

我对信号R核有一些问题,我无法从集线器向特定用户发送消息。 我想这样:

我需要向中心中的特定用户发送消息,但 我向所有连接在集线器中的用户发送了消息,然后将其过滤到java scrips文件中,然后根据ID将消息项追加到列表中

public JsonResult SendMessage(string id, string messagetext)
{
   _hubContext.Clients.All.SendAsync("LoadData", id, messagetext);
   return Json(1);
}

connection.on("LoadData", function (id,messageText) {
   var MyId = $('#UserIdLoggedIn').val();
   var message = messageText;
   if (MyId == id) {
       //appending 
           $("#header ul").append('<li class="him">' + message + '</li>');
       //appending end
   }
});

1 个答案:

答案 0 :(得分:0)

要将消息发送给特定用户,您需要具有其连接ID

首先,我将定义Hub,以便js代码可以调用Web服务器

public class ConnectionHub : Hub
    {
        public async Task Send(string userId)
        {
            var message = $"Send message to you with user id {userId}";
            await Clients.Client(userId).SendAsync("ReceiveMessage", message);
        }

        public string GetConnectionId()
        {
            return Context.ConnectionId;
        }
    }

然后在我的startup.cs

        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure(options =>
            {
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddSignalR();
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();
            app.UseCookiePolicy();
            app.UseSignalR(routes =>
            {
                routes.MapHub<ConnectionHub>("/connectionHub");
            });
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }

最后在Index.cshtml中,我将获得以下代码

(function () {
        var connection = new signalR.HubConnectionBuilder().withUrl("/connectionHub").build();

        connection.start().then(function () {
            console.log("connected");

            connection.invoke('getConnectionId')
                .then(function (connectionId) {
                    sessionStorage.setItem('conectionId', connectionId);
                    // Send the connectionId to controller
                }).catch(err => console.error(err.toString()));;


        });

        $("#sendmessage").click(function () {
            var connectionId = sessionStorage.getItem('conectionId');
            connection.invoke("Send", connectionId);
        });

        connection.on("ReceiveMessage", function (message) {
            console.log(message);
        });

    })();

您可以阅读我的完整博客here