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

Can't call client method from server

我正在尝试使用 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' does not contain a definition for 'addNewMessage' and no accessible extension method 'addNewMessage' accepting a first argument of type 'IClientProxy' could be found (are you missing a using directive or an assembly reference?)

我该如何解决这个问题?服务器代码包含在中心内。

这是因为您正在使用 ASP.NET Core SignalR 但您正在调用 ASP.NET MVC SignalR[=28 之后的客户端方法=].在 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());
});

并且在 Startup class SignalR 设置中应该如下:

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 本教程。