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

时间:2019-01-28 21:40:57

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

我正在尝试使用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指令或程序集引用?)

该如何解决?服务器代码包含在中心内。

1 个答案:

答案 0 :(得分:4)

这是因为您使用的是 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本教程进行操作。