【问题标题】:Startup Project - Blazor with SignalR. Server/Client启动项目 - 带有 SignalR 的 Blazor。服务器/客户端
【发布时间】:2020-04-28 18:16:07
【问题描述】:

我想开始使用 .NET blazor 和 SignalR。我将这个简单的 SignalR Blazor 应用程序作为教程开始。我找到了这个example。我已经逐步完成了这个例子几次,我一定是在看一些东西。我在 Visual Studio 19 上的 .Net Core 3.1 上运行这两个。服务器是启动项目,但是当我运行项目时 index.razor 不会被调用。我在演示中放入了正确的端点。但我无法点击客户端上的任何页面。我花了几个小时在这上面,感谢任何帮助。

endpoints.MapFallbackToFile("index.html");

这是我的服务器集线器类

using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR;
using SignalRTCBlazor.Shared.Models;
using System.Text.Json;


namespace SignalRTCBlazor.Server.Hubs
{
public class ChatHub : Hub
{

    public async Task NewUser(string username)
    {
        var userInfo = new UserInfo() { userName = username, connectionId = Context.ConnectionId };
        await Clients.Others.SendAsync("NewUserArrived", JsonSerializer.Serialize(userInfo));
    }

    public async Task HelloUser(string userName, string user)
    {
        var userInfo = new UserInfo() { userName = userName, connectionId = Context.ConnectionId };
        await Clients.Client(user).SendAsync("UserSaidHello", JsonSerializer.Serialize(userInfo));
    }

    public async Task SendSignal(string signal, string user)
    {
        await Clients.Client(user).SendAsync("SendSignal", Context.ConnectionId, signal);
    }

    public async Task SendMessage(string user, string message)
    {
        await Clients.All.SendAsync("ReceiveMessage", user, message);
    }

    public Task SendMessageToCaller(string message)
    {
        return Clients.Caller.SendAsync("ReceiveMessage", message);
    }

    public Task SendMessageToGroup(string message)
    {
        return Clients.Group("SignalR Users").SendAsync("ReceiveMessage", message);
    }

    public override async Task OnDisconnectedAsync(System.Exception exception)
    {
        await Clients.All.SendAsync("UserDisconnect", Context.ConnectionId);
        await base.OnDisconnectedAsync(exception);
    }
}
}

这是服务器启动

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using SignalRTCBlazor.Server.Hubs;
namespace SignalRTCBlazor.Server
{
 public class Startup
 {
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddRazorPages();
        services.AddServerSideBlazor();
        services.AddSignalR();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

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

        app.UseRouting();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapHub<ChatHub>("/chathub");
            endpoints.MapFallbackToFile("index.html");
        });
    }
 }
}

【问题讨论】:

    标签: c# asp.net asp.net-core signalr blazor


    【解决方案1】:

    我终于明白了。这么多设置,我还在学习。该示例说将以下行放入代码中。

       endpoints.MapHub<Hubs.ChatHub>(ChatClient.HUBURL);
       endpoints.MapFallbackToFile("index.html");
    

    并删除

         endpoints.MapBlazorHub();
         endpoints.MapFallbackToPage("/_Host");
    

    我所做的是把另外两行放进去就可以了

          endpoints.MapHub<Hubs.ChatHub>(ChatClient.HUBURL);
          endpoints.MapBlazorHub();
          endpoints.MapFallbackToPage("/_Host");
    

    【讨论】:

      【解决方案2】:

      首先在您的 Startup.cs 下的 ConfigureServices 添加中间件,如下所示:

      services.AddSignalR();
      

      然后在配置下,您可以像这样定义到您的集线器的路由:

       app.UseEndpoints(endpoints =>
         {
          endpoints.MapHub<Noty>("/notifyHub");
          endpoints.MapBlazorHub();
          ...
         });
      

      你需要编写你的 Hub 类,像这样,hub 有一个稍后会调用的 SetMessage 方法:

       public class Noty : Hub
          {
            private static IHubContext<Noty> _hubContext;
      
            public Noty(IHubContext<Noty> hubContext)
            {
                _hubContext = hubContext;
            }
            private async static Task SetMessage(string message)
            {
              await _hubContext.Clients.User(State.User.Current.Id).SendAsync("ReceiveMessage", message);
            }
          }
      

      最后,编写连接脚本(在 .js 文件中并在您的 _Host.cshtml 文件中引用它)

       $(document).ready(function () {
              var connection = new signalR.HubConnectionBuilder().withUrl("/notifyHub").build();
              connection.on("ReceiveMessage", function (message{      
                  alert(message);
              });
          });
      

      现在您可以在任何地方从您的中心调用 SendMessage,并且该中心会提醒该消息。

      【讨论】:

      • 我拥有所有这些,就像示例视频一样。 endpoints.MapDefaultControllerRoute(); endpoints.MapHub("/chatHub"); endpoints.MapFallbackToFile("index.html");
      • 试试我解释的代码,它可以工作,然后你可以自定义它。
      • 查看微软文档中的这个例子。 docs.microsoft.com/en-us/aspnet/core/tutorials/…
      • 我已经发布了我的服务器代码和启动文件。我遵循了这个例子。
      • 您的javascript代码似乎有问题。
      猜你喜欢
      • 2020-03-02
      • 1970-01-01
      • 2012-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多