无法从服务器调用客户端方法

问题描述 投票:0回答:1

我正在尝试使用SignalR从服务器向客户端广播消息,而客户端不会触发消息。从我见过的教程中,在客户端中定义一个方法,如下所示:

signalRConnection.client.addNewMessage = function(message) {
  console.log(message);
};

应该允许在服务器上使用以下集线器代码:

public async Task SendMessage(string message)
{
     await Clients.All.addNewMessage("Hey from the server!");
}

但是,Clients.All.addNewMessage调用会导致C#编译器出错:

'IClientProxy'不包含'addNewMessage'的定义,并且没有可访问的扩展方法'addNewMessage'接受类型'IClientProxy'的第一个参数(你是否缺少using指令或汇编引用?)

我该如何解决?服务器代码包含在集线器中。

asp.net asp.net-core signalr
1个回答
3
投票

这是因为您使用的是ASP.NET Core SignalR,但是您正在调用ASP.NET MVC SignalR之后的客户端方法。在ASP.NET Core SignalR中,您必须按如下方式调用客户端方法:

public async Task SendMessage(string message)
{
     await Clients.All.SendAsync("AddNewMessage", message); // here `AddNewMessage` is the method name in the client side.
}

它显示了您的客户端代码也适用于ASP.NET MVC SignalR。对于ASP.NET Core SignalR,它应该如下:

"use strict";

var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();

connection.on("AddNewMessage", function (message) {
    // do whatever you want to do with `message`
});

connection.start().catch(function (err) {
    return console.error(err.toString());
});

StartupSignalR设置应如下:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        services.AddMvc()
                .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

        services.AddSignalR(); // Must add this
    }

    // 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("/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseCookiePolicy();

        app.UseSignalR(routes =>
        {
            routes.MapHub<ChatHub>("/chatHub"); // Here is configuring for `ChatHub`
        });

        app.UseMvc();
    }
}

如果您面临更多问题,请关注Get started with ASP.NET Core SignalR本教程。

© www.soinside.com 2019 - 2024. All rights reserved.