.NET CORE 6.0 之SignalR 实时通讯

一、

创建 Web 应用项目

 

 

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

添加 SignalR 客户端库

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

  • 在“解决方案资源管理器”>中,右键单击项目,然后选择“添加”“客户端库”。
  • 在“添加客户端库”对话框中:
    • 为“提供程序”选择“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 文件。

       

       添加客户端

       

       

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      767
      <div class="container">
          <div class="row"> </div>
          <div class="row">
              <div class="col-2">User</div>
              <div class="col-4"><input type="text" id="userInput" /></div>
          </div>
          <div class="row">
              <div class="col-2">Message</div>
              <div class="col-4"><input type="text" id="messageInput" /></div>
          </div>
          <div class="row"> </div>
          <div class="row">
              <div class="col-6">
                  <input type="button" id="sendButton" value="Send Message" />
              </div>
          </div>
      </div>
      <div class="row">
          <div class="col-12">
              <hr />
          </div>
      </div>
      <div class="row">
          <div class="col-6">
              <ul id="messagesList"></ul>
          </div>
      </div>
      <script src="js/signalr/dist/browser/signalr.js"></script>
      <script src="chat.js"></script>

        

       

      chat.js

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      "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();
      });

        

      运行,跨域报错

      1
      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差不多:

posted on   topguntopgun  阅读(3481)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示