转帖官方教程:Tutorial: Getting Started with SignalR 2 and MVC 5

http://www.asp.net/signalr/overview/getting-started/tutorial-getting-started-with-signalr-and-mvc

This tutorial shows how to use ASP.NET SignalR 2 to create a real-time chat application. You will add SignalR to an MVC 5 application and create a chat view to send and display messages.

Software versions used in the tutorial

Using Visual Studio 2012 with this tutorial

Tutorial Versions

Questions and comments

Overview

This tutorial introduces you to real-time web application development with ASP.NET SignalR 2 and ASP.NET MVC 5. The tutorial uses the same chat application code as the SignalR Getting Started tutorial, but shows how to add it to an MVC 5 application.

In this topic you will learn the following SignalR development tasks:

  • Adding the SignalR library to an MVC 5 application.
  • Creating hub and OWIN startup classes to push content to clients.
  • Using the SignalR jQuery library in a web page to send messages and display updates from the hub.

The following screen shot shows the completed chat application running in a browser.

Sections:

Set up the Project

Prerequisites:

  • Visual Studio 2013. If you do not have Visual Studio, see ASP.NET Downloads to get the free Visual Studio 2013 Express Development Tool.

This section shows how to create an ASP.NET MVC 5 application, add the SignalR library, and create the chat application.

  1. In Visual Studio, create a C# ASP.NET application that targets .NET Framework 4.5, name it SignalRChat, and click OK.

  2. In the New ASP.NET Project dialog, and select MVC, and click Change Authentication.

  3. Select No Authentication in the Change Authentication dialog, and click OK.

    Note: If you select a different authentication provider for your application, a Startup.cs class will be created for you; you will not need to create your own Startup.cs class in step 10 below.

  4. Click OK in the New ASP.NET Project dialog.

  5. Open the Tools | Library Package Manager | Package Manager Console and run the following command. This step adds to the project a set of script files and assembly references that enable SignalR functionality.

    install-package Microsoft.AspNet.SignalR

  6. In Solution Explorer, expand the Scripts folder. Note that script libraries for SignalR have been added to the project.

  7. In Solution Explorer, right-click the project, select Add | New Folder, and add a new folder named Hubs.

  8. Right-click the Hubs folder, click Add | New Item, select the Visual C# | Web | SignalR node in the Installed pane, select SignalR Hub Class (v2) from the center pane, and create a new hub named ChatHub.cs. You will use this class as a SignalR server hub that sends messages to all clients.

  9. Replace the code in the ChatHub class with the following code.

    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);
    }
    }
    }
  10. Create a new class called Startup.cs. Change the contents of the file to the following.

    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();
    }
    }
    }
  11. Edit the HomeController class found in Controllers/HomeController.cs and add the following method to the class. This method returns the Chat view that you will create in a later step.

    public ActionResult Chat()
    {
    return View();
    }
  12. Right-click the Views/Home folder, and select Add... | View.

  13. In the Add View dialog, name the new view Chat.

  14. Replace the contents of Chat.cshtml with the following code.

    Important: When you add SignalR and other script libraries to your Visual Studio project, the Package Manager might install a version of the SignalR script file that is more recent than the version shown in this topic. Make sure that the script reference in your code matches the version of the script library installed in your project.

    @{
    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>
    }
  15. Save All for the project.

Run the Sample

  1. Press F5 to run the project in debug mode.

  2. In the browser address line, append /home/chat to the URL of the default page for the project. The Chat page loads in a browser instance and prompts for a user name.

  3. Enter a user name.

  4. Copy the URL from the address line of the browser and use it to open two more browser instances. In each browser instance, enter a unique user name.
  5. In each browser instance, add a comment and click Send. The comments should display in all browser instances.

    Note: This simple chat application does not maintain the discussion context on the server. The hub broadcasts comments to all current users. Users who join the chat later will see messages added from the time they join.

  6. The following screen shot shows the chat application running in a browser.

  7. In Solution Explorer, inspect the Script Documents node for the running application. This node is visible in debug mode if you are using Internet Explorer as your browser. There is a script file named hubs that the SignalR library dynamically generates at runtime. This file manages the communication between jQuery script and server-side code. If you use a browser other than Internet Explorer, you can also access the dynamic hubs file by browsing to it directly, for example http://mywebsite/signalr/hubs.

Examine the Code

The SignalR chat application demonstrates two basic SignalR development tasks: creating a hub as the main coordination object on the server, and using the SignalR jQuery library to send and receive messages.

SignalR Hubs

In the code sample the ChatHub class derives from the Microsoft.AspNet.SignalR.Hub class. Deriving from the Hub class is a useful way to build a SignalR application. You can create public methods on your hub class and then access those methods by calling them from scripts in a web page.

In the chat code, clients call the ChatHub.Send method to send a new message. The hub in turn sends the message to all clients by callingClients.All.addNewMessageToPage.

The Send method demonstrates several hub concepts :

  • Declare public methods on a hub so that clients can call them.

  • Use the Microsoft.AspNet.SignalR.Hub.Clients property to access all clients connected to this hub.
  • Call a function on the client (such as the addNewMessageToPage function) to update clients.

    public class ChatHub : Hub
    {
    public void Send(string name, string message)
    {
    Clients.All.addNewMessageToPage(name, message);
    }
    }
SignalR and jQuery

The Chat.cshtml view file in the code sample shows how to use the SignalR jQuery library to communicate with a SignalR hub. The essential tasks in the code are creating a reference to the auto-generated proxy for the hub, declaring a function that the server can call to push content to clients, and starting a connection to send messages to the hub.

The following code declares a reference to a hub proxy.

var chat = $.connection.chatHub; 

Note: In JavaScript the reference to the server class and its members is in camel case. The code sample references the C# ChatHub class in JavaScript as chatHub. If you want to reference the ChatHub class in jQuery with conventional Pascal casing as you would in C#, edit the ChatHub.cs class file. Add a using statement to reference the Microsoft.AspNet.SignalR.Hubs namespace. Then add the HubName attribute to the ChatHub class, for example [HubName("ChatHub")]. Finally, update your jQuery reference to the ChatHub class.

The following code shows how to create a callback function in the script. The hub class on the server calls this function to push content updates to each client. The optional call to the htmlEncode function shows a way to HTML encode the message content before displaying it in the page, as a way to prevent script injection.

chat.client.addNewMessageToPage = function (name, message) {
// Add the message to the page.
$('#discussion').append('<li><strong>' + htmlEncode(name)
+ '</strong>: ' + htmlEncode(message) + '</li>');
};

The following code shows how to open a connection with the hub. The code starts the connection and then passes it a function to handle the click event on the Send button in the Chat page.

Note: This approach ensures that the connection is established before the event handler executes.

$.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();
});
});

Next Steps

You learned that SignalR is a framework for building real-time web applications. You also learned several SignalR development tasks: how to add SignalR to an ASP.NET application, how to create a hub class, and how to send and receive messages from the hub.

For a walkthrough on how to deploy the sample SignalR application to Azure, see Using SignalR with Web Apps in Azure App Service. For detailed information about how to deploy a Visual Studio web project to a Windows Azure Web Site, see Create an ASP.NET web app in Azure App Service.

To learn more advanced SignalR developments concepts, visit the following sites for SignalR source code and resources :

SignalR 教程一的更多相关文章

  1. CRL快速开发框架系列教程一(Code First数据表不需再关心)

    本系列目录 CRL快速开发框架系列教程一(Code First数据表不需再关心) CRL快速开发框架系列教程二(基于Lambda表达式查询) CRL快速开发框架系列教程三(更新数据) CRL快速开发框 ...

  2. NGUI系列教程一

    NGUI是Unity的一个插件,使用它来制作你的游戏UI必定将事半功倍.为什么这么说呢?首先我们说说GUI与NGUI的区别,GUI是Unity自带的绘制界面工具,它的成像原理是基于表层的,所以执行效率 ...

  3. Quartz教程一:使用quartz

    原文链接 | 译文链接 | 翻译:nkcoder | 校对:方腾飞 本系列教程由quartz-2.2.x官方文档翻译.整理而来,希望给同样对quartz感兴趣的朋友一些参考和帮助,有任何不当或错误之处 ...

  4. redis学习教程一《Redis的安装和配置》

    redis学习教程一<Redis的安装和配置> Redis的优点 以下是Redis的一些优点. 异常快 - Redis非常快,每秒可执行大约110000次的设置(SET)操作,每秒大约可执 ...

  5. Cobalt Strike使用教程一

    Cobalt Strike使用教程一     0x00 简介 Cobalt Strike是一款基于java的渗透测试神器,常被业界人称为CS神器.自3.0以后已经不在使用Metasploit框架而作为 ...

  6. Activiti5.10简易教程一

    Activiti5.10简易教程一 一搭建环境 1.1   JDK 6+ activiti 运行在版本 6 以上的 JDK 上.转到 Oracle Java SE 下载页面,点击按钮“下载 JDK ” ...

  7. 无废话SharePoint入门教程一[SharePoint概述]

    一.前言 听说SharePoint也有一段时间了,可一直处在门外.最近被调到SharePoint实施项目小组,就随着工作一起学习了一下实施与开发.但苦于网上SharePoint入门的东西实在太少,导致 ...

  8. JavaScript 进阶教程一 JavaScript 中的事件流 - 事件冒泡和事件捕获

    先看下面的示例代码: <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Jav ...

  9. MVC5 + EF6 入门完整教程一:从0开始

    第0课 从0开始 ASP.NET MVC开发模式和传统的WebForm开发模式相比,增加了很多"约定". 直接讲这些 "约定" 会让人困惑,而且东西太多容易忘记 ...

随机推荐

  1. java温故而知新(8)反射机制

    一.什么是反射机制  简单的来说,反射机制指的是程序在运行时能够获取自身的信息.在java中,只要给定类的名字, 那么就可以通过反射机制来获得类的所有信息. 二.哪里用到反射机制  有些时候,我们用过 ...

  2. python2文件转换为exe可执行文件

    windows下py文件的运行需要安装python,如果是exe文件就可以直接运行 1. 直接在命令行用pip安装 pyinstaller pip install pyinstaller 2 在命令行 ...

  3. cf449D. Jzzhu and Numbers(容斥原理 高维前缀和)

    题意 题目链接 给出\(n\)个数,问任意选几个数,它们\(\&\)起来等于\(0\)的方案数 Sol 正解居然是容斥原理Orz,然而本蒟蒻完全想不到.. 考虑每一种方案 答案=任意一种方案 ...

  4. sqlserver查询当月数据

    SELECT * FROM table WHERE datediff(month,LoginTime,getdate())=0 ORDER BY LoginTime SELECT * FROM tab ...

  5. TextView的跑马灯效果(AS开发实战第二章学习笔记)

    TextView的跑马灯效果跑马灯用到的属性与方法说明singleLine 指定文本是否单行显示ellipsize 指定文本超出范围后的省略方式focusable 指定是否获得焦点,跑马灯效果要求设置 ...

  6. 抖音C#版,自己抓第三方抖音网站

    感谢http://dy.lujianqiang.com技术支持 文章更新:http://dy.lujianqiang.com这个服务器已经关了,现在没用了 版权归抖音公司所有,该博客只是为交流学习所使 ...

  7. Qt 之 QSS(样式表语法)

    https://blog.csdn.net/liang19890820/article/details/51691212 简述 Qt样式表(以下统称QSS)的术语和语法规则几乎和CSS相同.如果你熟悉 ...

  8. C# GDI+ 利用 Rectangle GraphicsPath 判断 矩形或多边形 图形关系

    最近在做一些简单的图像对比工作,总结了一些GDI+对象的使用方式,记录下来共享给大家使用. 判断Rectangl与多边形的关系 /// <summary> /// 是否包含输入范围 /// ...

  9. leetcode-surrounded regions-ZZ

    Problem Statement (link): Given a 2D board containing 'X' and 'O', capture all regions surrounded by ...

  10. sqlserver数据库使用空间监控

    数据库使用空间监控,并且每周发邮件预警,下面是操作步骤: 1:建立一张表 ), database_name ), file_group ), logical_name ), physical_name ...