接着上一篇:《ASP.NET SignalR系列》第四課 SignalR自托管(不用IIS)
一、概述
本教程主要闡釋了如何在MVC下使用ASP.NET SignalR。
- 添加SignalR庫到MVC中。
- 創建hub和OWIN startup 類來推送內容到客戶端。
- 在頁面中使用SignalR jQuery 庫發送消息和呈現從來得更新。
下面屏幕截圖展示了一個完成的聊天應用程序
二、創建項目
1.用MVC5 .NET4.5 創建一個名為SignalRChat的項目
2.改變授權.
3.選擇 No Authentication
注意: 如果你選擇了一個不一樣的授權方式有一個 Startup.cs
會自動為你創建; 在下面的步驟中,你就不必自己創建這個類了。
4.打開 Tools | Library Package Manager | Package Manager Console
install-package Microsoft.AspNet.SignalR
5.解決方案中已經為你添加了需要的東西了
6.在解決方案中給項目添加一個名為Hubs文件夾
7.在 Hubs文件夾中添加SignalR節點下的類文件, 名為ChatHub.cs. 可以使用這個類作為服務端hub發送消息到所有的客戶端。
8.類代碼
using System; using System.Web; using Microsoft.AspNet.SignalR; namespace SignalRChat { public class ChatHub : Hub { public void Send(string name, string message) { // Call the addNewMessageToPage method to update clients. Clients.All.addNewMessageToPage(name, message); } } }
7.創建Startup類
using Owin; using Microsoft.Owin; [assembly: OwinStartup(typeof(SignalRChat.Startup))] namespace SignalRChat { public class Startup { public void Configuration(IAppBuilder app) { // Any connection or hub wire up and configuration should go here app.MapSignalR(); } } }
8.在HomeController下添加一個action,名為Chat
public ActionResult Chat() { return View(); }
9.添加對應試圖
@{ ViewBag.Title = "Chat"; } <h2>Chat</h2> <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> @section scripts { <!--Script references. --> <!--The jQuery library is required and is referenced by default in _Layout.cshtml. --> <!--Reference the SignalR library. --> <script src="~/Scripts/jquery.signalR-2.1.0.min.js"></script> <!--Reference the autogenerated SignalR hub script. --> <script src="~/signalr/hubs"></script> <!--SignalR script to update the chat page and send messages.--> <script> $(function () { // Reference the auto-generated proxy for the hub. var chat = $.connection.chatHub; // Create a function that the hub can call back to display messages. chat.client.addNewMessageToPage = function (name, message) { // Add the message to the page. $('#discussion').append('<li><strong>' + htmlEncode(name) + '</strong>: ' + htmlEncode(message) + '</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. chat.server.send($('#displayname').val(), $('#message').val()); // Clear text box and reset focus for next comment. $('#message').val('').focus(); }); }); }); // This optional function html-encodes messages for display in the page. function htmlEncode(value) { var encodedValue = $('<div />').text(value).html(); return encodedValue; } </script> }
10.運行
11.代碼下載:點擊下載