"
ASP.NET (snapshot 2017) Microsoft documentation and samples

Tutorial: Getting Started with SignalR 2 and MVC 5

by Patrick Fletcher, Tim Teebken

Download Completed Project

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

To use Visual Studio 2012 with this tutorial, do the following:

  • Update your Package Manager to the latest version.
  • Install the Web Platform Installer.
  • In the Web Platform Installer, search for and install ASP.NET and Web Tools 2013.1 for Visual Studio 2012. This will install Visual Studio templates for SignalR classes such as Hub.
  • Some templates (such as OWIN Startup Class) will not be available; for these, use a Class file instead.

Tutorial Versions

For information about earlier versions of SignalR, see SignalR Older Versions.

Questions and comments

Please leave feedback on how you liked this tutorial and what we could improve in the comments at the bottom of the page. If you have questions that are not directly related to the tutorial, you can post them to the ASP.NET SignalR forum or StackOverflow.com.

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:

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

Chat instances
Chat instances

Sections:

Set up the Project

Prerequisites:

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.

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

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

    Select No Authentication
    Select No Authentication

    [!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.

    Scripts folder
  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.

    Create new hub
  9. Replace the code in the ChatHub class with the following code.

    [!code-csharpMain]
       1:  using System;
       2:  using System.Web;
       3:  using Microsoft.AspNet.SignalR;
       4:  namespace SignalRChat
       5:  {
       6:      public class ChatHub : Hub
       7:      {
       8:          public void Send(string name, string message)
       9:          {
      10:              // Call the addNewMessageToPage method to update clients.
      11:              Clients.All.addNewMessageToPage(name, message);
      12:          }
      13:      }
      14:  }
  10. Create a new class called Startup.cs. Change the contents of the file to the following.

    [!code-csharpMain]
       1:  using Owin;
       2:  using Microsoft.Owin;
       3:  [assembly: OwinStartup(typeof(SignalRChat.Startup))]
       4:  namespace SignalRChat
       5:  {
       6:      public class Startup
       7:      {
       8:          public void Configuration(IAppBuilder app)
       9:          {
      10:              // Any connection or hub wire up and configuration should go here
      11:              app.MapSignalR();
      12:          }
      13:      }
      14:  }
  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.

    [!code-csharpMain]
       1:  public ActionResult Chat()
       2:  {
       3:      return View();
       4:  }
  12. Right-click the Views/Home folder, and select Add??? | View.
  13. In the Add View dialog, name the new view Chat.

    Add a view
  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.

    [!code-cshtmlMain]
       1:  @{
       2:      ViewBag.Title = "Chat";
       3:  }
       4:  <h2>Chat</h2>
       5:  <div class="container">
       6:      <input type="text" id="message" />
       7:      <input type="button" id="sendmessage" value="Send" />
       8:      <input type="hidden" id="displayname" />
       9:      <ul id="discussion">
      10:      </ul>
      11:  </div>
      12:  @section scripts {
      13:      <!--Script references. -->
      14:      <!--The jQuery library is required and is referenced by default in _Layout.cshtml. -->
      15:      <!--Reference the SignalR library. -->
      16:      <script src="~/Scripts/jquery.signalR-2.1.0.min.js"></script>
      17:      <!--Reference the autogenerated SignalR hub script. -->
      18:      <script src="~/signalr/hubs"></script>
      19:      <!--SignalR script to update the chat page and send messages.--> 
      20:      <script>
      21:          $(function () {
      22:              // Reference the auto-generated proxy for the hub.  
      23:              var chat = $.connection.chatHub;
      24:              // Create a function that the hub can call back to display messages.
      25:              chat.client.addNewMessageToPage = function (name, message) {
      26:                  // Add the message to the page. 
      27:                  $('#discussion').append('<li><strong>' + htmlEncode(name) 
      28:                      + '</strong>: ' + htmlEncode(message) + '</li>');
      29:              };
      30:              // Get the user name and store it to prepend to messages.
      31:              $('#displayname').val(prompt('Enter your name:', ''));
      32:              // Set initial focus to message input box.  
      33:              $('#message').focus();
      34:              // Start the connection.
      35:              $.connection.hub.start().done(function () {
      36:                  $('#sendmessage').click(function () {
      37:                      // Call the Send method on the hub. 
      38:                      chat.server.send($('#displayname').val(), $('#message').val());
      39:                      // Clear text box and reset focus for next comment. 
      40:                      $('#message').val('').focus();
      41:                  });
      42:              });
      43:          });
      44:          // This optional function html-encodes messages for display in the page.
      45:          function htmlEncode(value) {
      46:              var encodedValue = $('<div />').text(value).html();
      47:              return encodedValue;
      48:          }
      49:      </script>
      50:  }
  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.

    Enter 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.

    Chat browsers
  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 calling Clients.All.addNewMessageToPage.

The Send method demonstrates several hub concepts :

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.

[!code-javascriptMain]

   1:  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.

[!code-htmlMain]

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

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.

[!code-javascriptMain]

   1:  $.connection.hub.start().done(function () {
   2:      $('#sendmessage').click(function () {
   3:          // Call the Send method on the hub. 
   4:          chat.server.send($('#displayname').val(), $('#message').val());
   5:          // Clear text box and reset focus for next comment. 
   6:          $('#message').val('').focus();
   7:      });
   8:  });

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 :



Comments ( )
Link to this page: //www.vb-net.com/AspNet-DocAndSamples-2017/aspnet/signalr/overview/getting-started/tutorial-getting-started-with-signalr-and-mvc.htm
< THANKS ME>