WTM (ASP.NET Core) uses SignalR, the background web page receives real-time message notifications

       In many web projects, there is such a requirement. The user performs an operation or database CURD, and the background page receives messages and pops up a window to prompt the administrator of the current operating system.

        Here we use Microsoft's SignalR real-time web function so that the server-side code can immediately push the content to the client. Please refer to the official Microsoft documentation for basic knowledge and installation . Our focus today is that WTM framework joins SignalR

1. Server

Configure SignalR in Program.cs in the WTM project.

1. Add in webBuilder.ConfigureServices method

x.AddSignalR();

2. Add in webBuilder.Configure method

 x.UseEndpoints(endpoints =>
                         {
                             endpoints.MapHub<ChatHub>("/chathub");
                         });

   3. Create a SignalR center

using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;

namespace SignalRChat.Hubs
{
    public class ChatHub : Hub
    {
        public async Task SendMessage(string user, string message)
        {
            await Clients.All.SendAsync("ReceiveMessage", user, message);
        }
    }
}

    4. Modify the _Layout.cshtml layout file, which is located in the Views/Shared directory

     Introduce the signalr.js obtained according to the official Microsoft documents into the file, and then write the SignalR connection and message reception processing code

<body>
    <div id="LAY_app"></div>
<script src="~/js/signalr/dist/browser/signalr.js"></script>
    <script src="/jquery.min.js"></script>
    <script src="/jquery.cookie.js"></script>
    <script src="/layui/layui.js"></script>
    <script src="/_js/[email protected]"></script>
<script>
    var DONOTUSE_IGNOREHASH = false;
    var DONOTUSE_COOKIEPRE = '@ViewData["DONOTUSE_COOKIEPRE"]';
    var DONOTUSE_WINDOWGUID = '@Guid.NewGuid().ToString().Replace("-", "")';
    layui.config({
        base: '/layuiadmin/'
        , version: '@DateTime.Now.Ticks'
    });
     //创建连接
     const connection = new signalR.HubConnectionBuilder()
        .withUrl("/chathub")
        .configureLogging(signalR.LogLevel.Information)
        .build();

    async function start() {
        try {
            await connection.start();
            console.log("SignalR Connected.");
        } catch (err) {
            console.log(err);
            setTimeout(start, 5000);
        }
    };

    connection.onclose(start);
    start();
    //接收数据并弹窗
        connection.on("ReceiveMessage", function (user, message) {

            layui.use('layer', function(){
                var layer = layui.layer;
                layer.msg(user+'||'+message, { time: 5000, icon: 6 });
            });     

        console.log(message);
    });
   
    </script>
    @RenderBody()
</body>

 Second, the client

1. Install the SignalR .net client package Microsoft.AspNetCore.SignalR.Client

2. Add the following code to the background method that needs to send data to complete the data sending to the background server

try
  {
     HubConnection connection = new HubConnectionBuilder()
                            .WithUrl(signalrUrl)
                            .Build();
     await connection.StartAsync();
     await connection.InvokeAsync("SendMessage",
     $"{user.UserType.UserTypeName}客户端", $"{DateTime.Now}数据发送");
   }
catch (Exception)
    {
    }

This completes some operations of the client to push messages to the server in real time. In addition to supporting .NET, SignalR also supports java and js. It is very convenient to write real-time applications. Real-time communication between time server and client can be achieved with very little code, allowing programmers to write code more focused.

Three, deployment

Deploy to iis must check the websocket protocol in the Windows function

 

 

Guess you like

Origin blog.csdn.net/sxy_student/article/details/108970196