.NET CORE 6.0 之SignalR 实时通讯


一、

创建 Web 应用项目

  1. 在“配置新项目”对话框中,为“项目名称”输入 SignalRChat。 请务必将项目命名为“SignalRChat”(包括匹配大小写),这样在复制和粘贴代码时命名空间就会匹配。

添加 SignalR 客户端库

ASP.NET Core 共享框架中包含 SignalR 服务器库。 JavaScript 客户端库不会自动包含在项目中。 对于此教程,使用库管理器 (LibMan) 从 unpkg 获取客户端库。 unpkg 是一个快速的全局内容分发网络,适用于 npm 上的所有内容。

  • Visual Studio
  • Visual Studio Code
  • Visual Studio for Mac
  • 在“解决方案资源管理器”>中,右键单击项目,然后选择“添加”“客户端库”。
  • 在“添加客户端库”对话框中:
    • 为“提供程序”选择“unpkg”
    • 对于“库”,输入 @microsoft/signalr@latest
    • 选择“选择特定文件”,展开“dist/browser”文件夹,然后选择 signalr.js 和 signalr.min.js
    • 将“目标位置”设置为 wwwroot/js/signalr/
    • 选择“安装”
          • 创建 SignalR 中心

            中心是一个类,用作处理客户端 - 服务器通信的高级管道。

            • 在 SignalRChat 项目文件夹中,创建 Hubs 文件夹。
            • 在 Hubs 文件夹中,使用以下代码创建 ChatHub 类:
            C#
            using Microsoft.AspNetCore.SignalR;
            
            namespace SignalRChat.Hubs
            {
                public class ChatHub : Hub
                {
                    public async Task SendMessage(string user, string message)
                    {
                        await Clients.All.SendAsync("ReceiveMessage", user, message);
                    }
                }
            }
    • hatHub 类继承自 SignalRHub。 Hub 类管理连接、组和消息。

      可通过已连接客户端调用 SendMessage,以向所有客户端发送消息。 本教程后面部分将显示调用该方法的 JavaScript 客户端代码。 SignalR 代码是异步模式,可提供最大的可伸缩性。

      配置 SignalR

      必须将 SignalR 服务器配置为将 SignalR 请求传递给 SignalR。 将以下突出显示的代码添加到 Program.cs 文件。

       添加客户端

      767
      
       
      User
      Message
       

          

        chat.js

        "use strict";
        var url = "http://localhost:5096"
        var connection = new signalR.HubConnectionBuilder().withUrl(url+"/chatHub").build();
        
        //Disable the send button until connection is established.
        document.getElementById("sendButton").disabled = true;
        
        connection.on("ReceiveMessage", function (user, message) {
            var li = document.createElement("li");
            document.getElementById("messagesList").appendChild(li);
            // We can assign user-supplied strings to an element's textContent because it
            // is not interpreted as markup. If you're assigning in any other way, you 
            // should be aware of possible script injection concerns.
            li.textContent = `${user} says ${message}`;
        });
        
        connection.start().then(function () {
            document.getElementById("sendButton").disabled = false;
        }).catch(function (err) {
            return console.error(err.toString());
        });
        
        document.getElementById("sendButton").addEventListener("click", function (event) {
            var user = document.getElementById("userInput").value;
            var message = document.getElementById("messageInput").value;
            connection.invoke("SendMessage", user, message).catch(function (err) {
                return console.error(err.toString());
            });
            event.preventDefault();
        });
        

        运行,跨域报错

        Access to fetch at 'http://localhost:5096/chatHub/negotiate?negotiateVersion=1' from origin 'http://127.0.0.1:8848' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
        
        解决方法
      • builder.Services.AddCors(options => options.AddPolicy("CorsPolicy",
        set =>
        {
        set.SetIsOriginAllowed(origin => true)//这个必须加
        .AllowAnyHeader()
        .AllowAnyMethod()
        .AllowCredentials();//这个一定不能少

        }));

      • 通过控制器像客户端发送信息

      •  

      • 调用其他地方的服务

      •   

        授权和验证

        SignalR会采用ASP.NET Core配置好的授权和验证体系.

        用法和Controller差不多: