接着上一篇:《ASP.NET SignalR系列》第四課 SignalR自託管(不用IIS)html
本教程主要闡釋瞭如何在MVC下使用ASP.NET SignalR。jquery
下面屏幕截圖展現了一個完成的聊天應用程序web
1.用MVC5 .NET4.5 建立一個名爲SignalRChat的項目mvc
2.改變受權.app
3.選擇 No Authenticationasp.net
注意: 若是你選擇了一個不同的受權方式有一個 Startup.cs
會自動爲你建立; 在下面的步驟中,你就沒必要本身建立這個類了。ui
4.打開 Tools | Library Package Manager | Package Manager Consolespa
install-package Microsoft.AspNet.SignalR
.net
5.解決方案中已經爲你添加了須要的東西了code
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.代碼下載:點擊下載