1. 程式人生 > 實用技巧 >SignalR 簡易聊天室+SignalR如何跨域

SignalR 簡易聊天室+SignalR如何跨域

十年河東,十年河西,莫欺少年窮

學無止境,精益求精

環境:VS2012或以上,Frm版本4.5或以上,我用的是4.5.2

1、在 Visual Studio 中,建立一個 ASP.NET MVC Web 應用程式。

2、右鍵專案,新增hub類,並命名為:ChatHub【新增後,專案會自動引用SignalR的相關DLL程式集及會在Scripts檔案中生成SignalR客戶端JS檔案】

JS如下:

ChatHub 類的程式碼如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR; using System.Threading.Tasks; namespace SignalRTx.ChatHubServer { public class ChatHub : Hub { public static List<string> Connectedlst = new List<string>(); /// <summary> /// 當客戶端連線時 /// </summary> /// <returns></returns>
public override Task OnConnected() { var ConnectionId = Context.ConnectionId; Connectedlst.Add(ConnectionId); return base.OnConnected(); } /// <summary> /// 當客戶端斷開連線時,例如使用者關閉頁面,重新整理頁面 /// </summary> /// <param name="stopCalled"></param>
/// <returns></returns> public override Task OnDisconnected(bool stopCalled) { var ConnectionId = Context.ConnectionId; Connectedlst.Remove(ConnectionId); return base.OnDisconnected(stopCalled); } /// <summary> /// 當客戶端重連時 /// </summary> /// <returns></returns> public override Task OnReconnected() { var ConnectionId = Context.ConnectionId; if (!Connectedlst.Contains(ConnectionId)) { Connectedlst.Add(ConnectionId); } return base.OnReconnected(); } /// <summary> /// 這是一組廣播訊息 所有客戶端均可收到此訊息 /// broadcastMessage 是客戶端的一個JS方法,也是回撥函式,用於更新客戶端 /// send 則是服務端的方法,用於客戶端呼叫 /// </summary> /// <param name="name"></param> /// <param name="message"></param> public void Send(string name, string message) { Clients.All.broadcastMessage(name, message); } } }
View Code

在專案中新增命名為Startup的類,如下:

using System;
using Microsoft.AspNet.SignalR;
using Microsoft.Owin;
using Microsoft.Owin.Cors;
using Owin;

[assembly: OwinStartup(typeof(SignalRTx.ChatHubServer.Startup))]
namespace SignalRTx.ChatHubServer
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // Any connection or hub wire up and configuration should go here
            app.MapSignalR();
        }
    }


}
View Code

在解決方案資源管理器中,右鍵單擊專案,然後選擇 "新增> "HTML 頁",如下:

<!DOCTYPE html>
<html>
<head>
    <title>SignalR Simple Chat</title>
    <style type="text/css">
        .container {
            background-color: #99CCFF;
            border: thick solid #808080;
            padding: 20px;
            margin: 20px;
        }
    </style>
</head>
<body>
    <div class="container">
        <input type="text" id="message" />
        <input type="button" id="sendmessage" value="Send" />
        <input type="hidden" id="displayname" />
        <ul id="discussion">
        </ul>
    </div>
    <!--Script references. -->
    <!--Reference the jQuery library. -->
    <script src="Scripts/jquery-3.4.1.js"></script>
    <!--Reference the SignalR library. -->
    <script src="Scripts/jquery.signalR-2.2.2.js"></script>
    <!--Reference the autogenerated SignalR hub script. -->
    <script src="signalr/hubs"></script>
    <!--Add script to update the page and send messages.-->
    <script type="text/javascript">
        $(function () {
            // Declare a proxy to reference the hub.
            var chat = $.connection.chatHub;
            // Create a function that the hub can call to broadcast messages.
            chat.client.broadcastMessage = function (name, message) {
                // Html encode display name and message.
                var encodedName = $('<div />').text(name).html();
                var encodedMsg = $('<div />').text(message).html();
                // Add the message to the page.
                $('#discussion').append('<li><strong>' + encodedName
                    + '</strong>:&nbsp;&nbsp;' + encodedMsg + '</li>');
            };
            // Get the user name and store it to prepend to messages.
            $('#displayname').val(prompt('Enter your name:', ''));
            // Set initial focus to message input box.
            $('#message').focus();
            // Start the connection.
            $.connection.hub.start().done(function () {
                $('#sendmessage').click(function () {
                    // Call the Send method on the hub.【服務端方法:send】
                    chat.server.send($('#displayname').val(), $('#message').val());
                    // Clear text box and reset focus for next comment.
                    $('#message').val('').focus();
                });
            });
        });
    </script>
</body>
</html>
View Code

執行這個HTML頁面,效果如下:

聊天內容雖說不那麼好吧,但我們對SignalR如何實現跨域還是非常認真的,那麼怎麼操作才可以跨域通訊呢?

要實現SigNalR跨域,首選我們需要安裝一個包,執行如下命令:

Install-Package Microsoft.Owin.Cors

然後修改我們的Startup類,如下:

using System;
using Microsoft.AspNet.SignalR;
using Microsoft.Owin;
using Microsoft.Owin.Cors;
using Owin;

[assembly: OwinStartup(typeof(SignalRTx.ChatHubServer.Startup))]
namespace SignalRTx.ChatHubServer
{
    //public class Startup
    //{
    //    public void Configuration(IAppBuilder app)
    //    {
    //        // Any connection or hub wire up and configuration should go here
    //        app.MapSignalR();
    //    }
    //}

    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // Branch the pipeline here for requests that start with "/signalr"
            app.Map("/signalr", map =>
            {
                // Setup the CORS middleware to run before SignalR.
                // By default this will allow all origins. You can 
                // configure the set of origins and/or http verbs by
                // providing a cors options with a different policy.
                map.UseCors(CorsOptions.AllowAll);
                var hubConfiguration = new HubConfiguration
                {
                     //You can enable JSONP by uncommenting line below.
                     //JSONP requests are insecure but some older browsers (and some
                     //versions of IE) require JSONP to work cross domain
                     EnableJSONP = true
                };
                // Run the SignalR pipeline. We're not using MapSignalR
                // since this branch already runs under the "/signalr"
                // path.
                map.RunSignalR(hubConfiguration);
            });
        }
    }
}
View Code

首先把你的專案複製一個副本出來,放到其他資料夾中,然後修改你複製專案的執行埠號,如下:

最後,客戶端動態引用指定URL及埠號的signalR,修改副本HTML如下:

<!DOCTYPE html>
<html>
<head>
    <title>SignalR Simple Chat</title>
    <style type="text/css">
        .container {
            background-color: #99CCFF;
            border: thick solid #808080;
            padding: 20px;
            margin: 20px;
        }
    </style>
</head>
<body>
    <div class="container">
        <input type="text" id="message" />
        <input type="button" id="sendmessage" value="Send" />
        <input type="hidden" id="displayname" />
        <ul id="discussion">
        </ul>
    </div>
    <!--Script references. -->
    <!--Reference the jQuery library. -->
    <script src="Scripts/jquery-3.4.1.js"></script>
    <!--Reference the SignalR library. -->
    <script src="Scripts/jquery.signalR-2.2.2.js"></script>
    <!--Reference the autogenerated SignalR hub script. -->
    <script src="https://localhost:44330/signalr/hubs"></script>
    <!--Add script to update the page and send messages.-->
    <script type="text/javascript">
        $(function () {
            // Declare a proxy to reference the hub.
            var chat = $.connection.chatHub;
            chat.connection.url = "https://localhost:44330/signalr";
            // Create a function that the hub can call to broadcast messages.
            chat.client.broadcastMessage = function (name, message) {
                // Html encode display name and message.
                var encodedName = $('<div />').text(name).html();
                var encodedMsg = $('<div />').text(message).html();
                // Add the message to the page.
                $('#discussion').append('<li><strong>' + encodedName
                    + '</strong>:&nbsp;&nbsp;' + encodedMsg + '</li>');
            };
            // Get the user name and store it to prepend to messages.
            $('#displayname').val(prompt('Enter your name:', ''));
            // Set initial focus to message input box.
            $('#message').focus();
            // Start the connection.
            $.connection.hub.start().done(function () {
                $('#sendmessage').click(function () {
                    // Call the Send method on the hub.【服務端方法:send】
                    chat.server.send($('#displayname').val(), $('#message').val());
                    // Clear text box and reset focus for next comment.
                    $('#message').val('').focus();
                });
            });
        });
    </script>
</body>
</html>
View Code

變更點:

這樣就可以跨域了,下面我們來模擬下跨域的請求,如下:

1、啟動並除錯服務端專案,埠為:44330,並把chathub所有方法都打上斷點,

/2、啟動不除錯你的副本專案,埠為:44333,我們通過觀察斷點是否能進入判斷跨域請求是否成功

證明跨域訪問成功。

聊天內容如下:

參考文獻:

https://docs.microsoft.com/zh-cn/aspnet/signalr/overview/getting-started/introduction-to-signalr

https://docs.microsoft.com/zh-cn/aspnet/signalr/overview/guide-to-the-api/hubs-api-guide-javascript-client

https://docs.microsoft.com/zh-cn/aspnet/signalr/overview/getting-started/tutorial-getting-started-with-signalr

https://blog.csdn.net/tte_w/article/details/80881060