ASP.net SignalR Hubs API Guide - JavaScript Client _ the ASP

19
8/10/2015 ASP.NET SignalR Hubs API Guide JavaScript Client | The ASP.NET Site http://www.asp.net/signalr/overview/guidetotheapi/hubsapiguidejavascriptclient 1/19 This document provides an introduction to using the Hubs API for SignalR version 2 in JavaScript clients, such as browsers and Windows Store ﴾WinJS﴿ applications. The SignalR Hubs API enables you to make remote procedure calls ﴾RPCs﴿ from a server to connected clients and from clients to the server. In server code, you define methods that can be called by clients, and you call methods that run on the client. In client code, you define methods that can be called from the server, and you call methods that run on the server. SignalR takes care of all of the client‐to‐server plumbing for you. SignalR also offers a lower‐level API called Persistent Connections. For an introduction to SignalR, Hubs, and Persistent Connections, see Introduction to SignalR ﴾/signalr/overview/signalr‐20/getting‐started‐with‐signalr‐ 20/introduction‐to‐signalr﴿ . Software versions used in this topic Previous versions of this topic Questions and comments Overview This document contains the following sections: The generated proxy and what it does for you ﴾#genproxy﴿ When to use the generated proxy ﴾#cantusegenproxy﴿ Client Setup ﴾#clientsetup﴿ How to reference the dynamically generated proxy ﴾#dynamicproxy﴿ How to create a physical file for the SignalR generated proxy ﴾#manualproxy﴿ How to establish a connection ﴾#establishconnection﴿ $.connection.hub is the same object that $.hubConnection﴾﴿ creates ﴾#connequivalence﴿ Asynchronous execution of the start method ﴾#asyncstart﴿ How to establish a cross‐domain connection ﴾#crossdomain﴿ How to configure the connection ﴾#configureconnection﴿ How to specify query string parameters ﴾#querystring﴿ How to specify the transport method ﴾#transport﴿ How to get a proxy for a Hub class ﴾#getproxy﴿ How to define methods on the client that the server can call ﴾#callclient﴿ How to call server methods from the client ﴾#callserver﴿ By Tom Dykstra and Patrick Fletcher | June 10, 2014 | Level 100 : Beginner ASP.NET SignalR Hubs API Guide ‐ JavaScript Client

description

ASP.NET SignalR Hubs API Guide - JavaScript Client _ The ASP.pdf

Transcript of ASP.net SignalR Hubs API Guide - JavaScript Client _ the ASP

Page 1: ASP.net SignalR Hubs API Guide - JavaScript Client _ the ASP

8/10/2015 ASP.NET SignalR Hubs API Guide ­ JavaScript Client | The ASP.NET Site

http://www.asp.net/signalr/overview/guide­to­the­api/hubs­api­guide­javascript­client 1/19

This document provides an introduction to using the Hubs API for SignalR version 2 in JavaScript clients, such asbrowsers and Windows Store ﴾WinJS﴿ applications.

The SignalR Hubs API enables you to make remote procedure calls ﴾RPCs﴿ from a server to connected clientsand from clients to the server. In server code, you define methods that can be called by clients, and you callmethods that run on the client. In client code, you define methods that can be called from the server, and youcall methods that run on the server. SignalR takes care of all of the client‐to‐server plumbing for you.

SignalR also offers a lower‐level API called Persistent Connections. For an introduction to SignalR, Hubs, andPersistent Connections, see Introduction to SignalR ﴾/signalr/overview/signalr‐20/getting‐started‐with‐signalr‐20/introduction‐to‐signalr﴿ .

Software versions used in this topicPrevious versions of this topicQuestions and comments

OverviewThis document contains the following sections:

The generated proxy and what it does for you ﴾#genproxy﴿

When to use the generated proxy ﴾#cantusegenproxy﴿

Client Setup ﴾#clientsetup﴿

How to reference the dynamically generated proxy ﴾#dynamicproxy﴿

How to create a physical file for the SignalR generated proxy ﴾#manualproxy﴿

How to establish a connection ﴾#establishconnection﴿

$.connection.hub is the same object that $.hubConnection﴾﴿ creates ﴾#connequivalence﴿

Asynchronous execution of the start method ﴾#asyncstart﴿

How to establish a cross‐domain connection ﴾#crossdomain﴿

How to configure the connection ﴾#configureconnection﴿

How to specify query string parameters ﴾#querystring﴿

How to specify the transport method ﴾#transport﴿

How to get a proxy for a Hub class ﴾#getproxy﴿

How to define methods on the client that the server can call ﴾#callclient﴿

How to call server methods from the client ﴾#callserver﴿

By Tom Dykstra and Patrick Fletcher | June 10, 2014 | Level 100 : Beginner

ASP.NET SignalR Hubs API Guide ‐ JavaScriptClient

Page 2: ASP.net SignalR Hubs API Guide - JavaScript Client _ the ASP

8/10/2015 ASP.NET SignalR Hubs API Guide ­ JavaScript Client | The ASP.NET Site

http://www.asp.net/signalr/overview/guide­to­the­api/hubs­api­guide­javascript­client 2/19

How to handle connection lifetime events ﴾#connectionlifetime﴿

How to handle errors ﴾#handleerrors﴿

How to enable client‐side logging ﴾#logging﴿

For documentation on how to program the server or .NET clients, see the following resources:

SignalR Hubs API Guide ‐ Server ﴾/signalr/overview/signalr‐20/hubs‐api/hubs‐api‐guide‐server﴿

SignalR Hubs API Guide ‐ .NET Client ﴾/signalr/overview/signalr‐20/hubs‐api/hubs‐api‐guide‐net‐client﴿

The SignalR 2 server component is only available on .NET 4.5 ﴾though there is a .NET client for SignalR 2 on .NET 4.0﴿.

The generated proxy and what it does for youYou can program a JavaScript client to communicate with a SignalR service with or without a proxy that SignalRgenerates for you. What the proxy does for you is simplify the syntax of the code you use to connect, write methodsthat the server calls, and call methods on the server.

When you write code to call server methods, the generated proxy enables you to use syntax that looks as though youwere executing a local function: you can write serverMethod(arg1, arg2) instead of invoke('serverMethod',arg1, arg2). The generated proxy syntax also enables an immediate and intelligible client‐side error if you mistypea server method name. And if you manually create the file that defines the proxies, you can also get IntelliSensesupport for writing code that calls server methods.

For example, suppose you have the following Hub class on the server:

public class ContosoChatHub : Hub{    public void NewContosoChatMessage(string name, string message)    {        Clients.All.addContosoChatMessageToPage(name, message);    }}

The following code examples show what JavaScript code looks like for invoking the NewContosoChatMessagemethod on the server and receiving invocations of the addContosoChatMessageToPage method from the server.

With the generated proxy

var contosoChatHubProxy = $.connection.contosoChatHub;contosoChatHubProxy.client.addContosoChatMessageToPage = function (name, message) {    console.log(name + ' ' + message);};$.connection.hub.start().done(function () {    // Wire up Send button to call NewContosoChatMessage on the server.    $('#newContosoChatMessage').click(function () {         contosoChatHubProxy.server.newContosoChatMessage($('#displayname').val(), $('#message').val());         $('#message').val('').focus();

Page 3: ASP.net SignalR Hubs API Guide - JavaScript Client _ the ASP

8/10/2015 ASP.NET SignalR Hubs API Guide ­ JavaScript Client | The ASP.NET Site

http://www.asp.net/signalr/overview/guide­to­the­api/hubs­api­guide­javascript­client 3/19

     });});

Without the generated proxy

var connection = $.hubConnection();var contosoChatHubProxy = connection.createHubProxy('contosoChatHub');contosoChatHubProxy.on('addContosoChatMessageToPage', function(name, message) {    console.log(name + ' ' + message);});connection.start().done(function() {    // Wire up Send button to call NewContosoChatMessage on the server.    $('#newContosoChatMessage').click(function () {        contosoChatHubProxy.invoke('newContosoChatMessage', $('#displayname').val(), $('#message').val());        $('#message').val('').focus();                });    });

When to use the generated proxyIf you want to register multiple event handlers for a client method that the server calls, you can't use the generatedproxy. Otherwise, you can choose to use the generated proxy or not based on your coding preference. If you choosenot to use it, you don't have to reference the "signalr/hubs" URL in a script element in your client code.

Client setupA JavaScript client requires references to jQuery and the SignalR core JavaScript file. The jQuery version must be 1.6.4or major later versions, such as 1.7.2, 1.8.2, or 1.9.1. If you decide to use the generated proxy, you also need areference to the SignalR generated proxy JavaScript file. The following example shows what the references might looklike in an HTML page that uses the generated proxy.

<script src="Scripts/jquery‐1.10.2.min.js"></script><script src="Scripts/jquery.signalR‐2.1.0.min.js"></script><script src="signalr/hubs"></script>

These references must be included in this order: jQuery first, SignalR core after that, and SignalR proxies last.

How to reference the dynamically generated proxyIn the preceding example, the reference to the SignalR generated proxy is to dynamically generated JavaScript code,not to a physical file. SignalR creates the JavaScript code for the proxy on the fly and serves it to the client inresponse to the "/signalr/hubs" URL. If you specified a different base URL for SignalR connections on the server inyour MapSignalR method, the URL for the dynamically generated proxy file is your custom URL with "/hubs"appended to it.

Note: For Windows 8 ﴾Windows Store﴿ JavaScript clients, use the physical proxy file instead of

Page 4: ASP.net SignalR Hubs API Guide - JavaScript Client _ the ASP

8/10/2015 ASP.NET SignalR Hubs API Guide ­ JavaScript Client | The ASP.NET Site

http://www.asp.net/signalr/overview/guide­to­the­api/hubs­api­guide­javascript­client 4/19

In an ASP.NET MVC 4 or 5 Razor view, use the tilde to refer to the application root in your proxy file reference:

<script src="~/signalr/hubs"></script>

For more information about using SignalR in MVC 5, see Getting Started with SignalR and MVC 5﴾/signalr/overview/signalr‐20/getting‐started‐with‐signalr‐20/tutorial‐getting‐started‐with‐signalr‐20‐and‐mvc‐5﴿ .

In an ASP.NET MVC 3 Razor view, use Url.Content for your proxy file reference:

<script src="@Url.Content("~/signalr/hubs")"></script>

In an ASP.NET Web Forms application, use ResolveClientUrl for your proxies file reference or register it via theScriptManager using an app root relative path ﴾starting with a tilde﴿:

<script src='<%: ResolveClientUrl("~/signalr/hubs") %>'></script>

As a general rule, use the same method for specifying the "/signalr/hubs" URL that you use for CSS or JavaScript files.If you specify a URL without using a tilde, in some scenarios your application will work correctly when you test inVisual Studio using IIS Express but will fail with a 404 error when you deploy to full IIS. For more information, seeResolving References to Root‐Level Resources in Web Servers in Visual Studio for ASP.NET Web Projects﴾http://msdn.microsoft.com/en‐us/library/58wxa9w5.aspx﴿ on the MSDN site.

When you run a web project in Visual Studio 2013 in debug mode, and if you use Internet Explorer as your browser,you can see the proxy file in Solution Explorer under Script Documents, as shown in the following illustration.

To see the contents of the file, double‐click hubs. If you are not using Visual Studio 2012 or 2013 and InternetExplorer, or if you are not in debug mode, you can also get the contents of the file by browsing to the"/signalR/hubs" URL. For example, if your site is running at http://localhost:56699, go tohttp://localhost:56699/SignalR/hubs in your browser.

How to create a physical file for the SignalR generated proxyAs an alternative to the dynamically generated proxy, you can create a physical file that has the proxy code andreference that file. You might want to do that for control over caching or bundling behavior, or to get IntelliSensewhen you are coding calls to server methods.

To create a proxy file, perform the following steps:

1. Install the Microsoft.AspNet.SignalR.Utils ﴾https://nuget.org/packages/Microsoft.AspNet.SignalR.Utils/﴿ NuGetpackage.

the dynamically generated one. For more information, see How to create a physical file for theSignalR generated proxy ﴾#manualproxy﴿ later in this topic.

Page 5: ASP.net SignalR Hubs API Guide - JavaScript Client _ the ASP

8/10/2015 ASP.NET SignalR Hubs API Guide ­ JavaScript Client | The ASP.NET Site

http://www.asp.net/signalr/overview/guide­to­the­api/hubs­api­guide­javascript­client 5/19

2. Open a command prompt and browse to the tools folder that contains the SignalR.exe file. The tools folder is atthe following location:

[your solution folder]\packages\Microsoft.AspNet.SignalR.Utils.2.1.0\tools

3. Enter the following command:

signalr ghp /path:[path to the .dll that contains your Hub class]

The path to your .dll is typically the bin folder in your project folder.

This command creates a file named server.js in the same folder as signalr.exe.

4. Put the server.js file in an appropriate folder in your project, rename it as appropriate for your application, andadd a reference to it in place of the "signalr/hubs" reference.

How to establish a connectionBefore you can establish a connection, you have to create a connection object, create a proxy, and register eventhandlers for methods that can be called from the server. When the proxy and event handlers are set up, establish theconnection by calling the start method.

If you are using the generated proxy, you don't have to create the connection object in your own code because thegenerated proxy code does it for you.

Establish a connection ﴾with the generated proxy﴿

var contosoChatHubProxy = $.connection.contosoChatHub;contosoChatHubProxy.client.addContosoChatMessageToPage = function (name, message) {    console.log(userName + ' ' + message);};$.connection.hub.start()    .done(function(){ console.log('Now connected, connection ID=' + $.connection.hub.id); })    .fail(function(){ console.log('Could not Connect!'); });});

Establish a connection ﴾without the generated proxy﴿

var connection = $.hubConnection();var contosoChatHubProxy = connection.createHubProxy('contosoChatHub');contosoChatHubProxy.on('addContosoChatMessageToPage', function(userName, message) {    console.log(userName + ' ' + message);});connection.start()    .done(function(){ console.log('Now connected, connection ID=' + connection.id); })    .fail(function(){ console.log('Could not connect'); });

The sample code uses the default "/signalr" URL to connect to your SignalR service. For information about how to

Page 6: ASP.net SignalR Hubs API Guide - JavaScript Client _ the ASP

8/10/2015 ASP.NET SignalR Hubs API Guide ­ JavaScript Client | The ASP.NET Site

http://www.asp.net/signalr/overview/guide­to­the­api/hubs­api­guide­javascript­client 6/19

specify a different base URL, see ASP.NET SignalR Hubs API Guide ‐ Server ‐ The /signalr URL﴾/signalr/overview/signalr‐20/hubs‐api/hubs‐api‐guide‐server#signalrurl﴿ .

$.connection.hub is the same object that $.hubConnection﴾﴿ createsAs you can see from the examples, when you use the generated proxy, $.connection.hub refers to the connectionobject. This is the same object that you get by calling $.hubConnection() when you aren't using the generatedproxy. The generated proxy code creates the connection for you by executing the following statement:

When you're using the generated proxy, you can do anything with $.connection.hub that you can do with aconnection object when you're not using the generated proxy.

Asynchronous execution of the start methodThe start method executes asynchronously. It returns a jQuery Deferred object﴾http://api.jquery.com/category/deferred‐object/﴿ , which means that you can add callback functions by callingmethods such as pipe, done, and fail. If you have code that you want to execute after the connection is established,such as a call to a server method, put that code in a callback function or call it from a callback function. The .donecallback method is executed after the connection has been established, and after any code that you have in yourOnConnected event handler method on the server finishes executing.

If you put the "Now connected" statement from the preceding example as the next line of code after the startmethod call ﴾not in a .done callback﴿, the console.log line will execute before the connection is established, asshown in the following example:

Note: Normally you register event handlers before calling the start method to establish theconnection. If you want to register some event handlers after establishing the connection, youcan do that, but you must register at least one of your event handler﴾s﴿ before calling the startmethod. One reason for this is that there can be many Hubs in an application, but you wouldn'twant to trigger the OnConnected event on every Hub if you are only going to use to one ofthem. When the connection is established, the presence of a client method on a Hub's proxy iswhat tells SignalR to trigger the OnConnected event. If you don't register any event handlersbefore calling the start method, you will be able to invoke methods on the Hub, but the Hub'sOnConnected method won't be called and no client methods will be invoked from the server.

Page 7: ASP.net SignalR Hubs API Guide - JavaScript Client _ the ASP

8/10/2015 ASP.NET SignalR Hubs API Guide ­ JavaScript Client | The ASP.NET Site

http://www.asp.net/signalr/overview/guide­to­the­api/hubs­api­guide­javascript­client 7/19

 

How to establish a cross‐domain connectionTypically if the browser loads a page from http://contoso.com, the SignalR connection is in the same domain, athttp://contoso.com/signalr. If the page from http://contoso.com makes a connection tohttp://fabrikam.com/signalr, that is a cross‐domain connection. For security reasons, cross‐domain connectionsare disabled by default.

In SignalR 1.x, cross domain requests were controlled by a single EnableCrossDomain flag. This flag controlled bothJSONP and CORS requests. For greater flexibility, all CORS support has been removed from the server component ofSignalR ﴾JavaScript clients still use CORS normally if it is detected that the browser supports it﴿, and new OWINmiddleware has been made available to support these scenarios.

If JSONP is required on the client ﴾to support cross‐domain requests in older browsers﴿, it will need to be enabledexplicitly by setting EnableJSONP on the HubConfiguration object to true, as shown below. JSONP is disabled bydefault, as it is less secure than CORS.

Adding Microsoft.Owin.Cors to your project: To install this library, run the following command in the PackageManager Console:

Install‐Package Microsoft.Owin.CorsThis command will add the 2.1.0 version of the package to your project.

Calling UseCorsThe following code snippet demonstrates how to implement cross‐domain connections in SignalR 2.Implementing cross‐domain requests in SignalR 2

The following code demonstrates how to enable CORS or JSONP in a SignalR 2 project. This code sample uses Mapand RunSignalR instead of MapSignalR, so that the CORS middleware runs only for the SignalR requests that requireCORS support ﴾rather than for all traffic at the path specified in MapSignalR.﴿ Map can also be used for any othermiddleware that needs to run for a specific URL prefix, rather than for the entire application.

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

Page 8: ASP.net SignalR Hubs API Guide - JavaScript Client _ the ASP

8/10/2015 ASP.NET SignalR Hubs API Guide ­ JavaScript Client | The ASP.NET Site

http://www.asp.net/signalr/overview/guide­to­the­api/hubs­api­guide­javascript­client 8/19

using Owin;namespace MyWebApplication{    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);            });        }    }}

Notes:

Don't set jQuery.support.cors to true in your code.

SignalR handles the use of CORS. Setting jQuery.support.cors to true disables JSONPbecause it causes SignalR to assume the browser supports CORS.

When you're connecting to a localhost URL, Internet Explorer 10 won't consider it a cross‐domain connection, so the application will work locally with IE 10 even if you haven'tenabled cross‐domain connections on the server.

For information about using cross‐domain connections with Internet Explorer 9, see this

Page 9: ASP.net SignalR Hubs API Guide - JavaScript Client _ the ASP

8/10/2015 ASP.NET SignalR Hubs API Guide ­ JavaScript Client | The ASP.NET Site

http://www.asp.net/signalr/overview/guide­to­the­api/hubs­api­guide­javascript­client 9/19

How to configure the connectionBefore you establish a connection, you can specify query string parameters or specify the transport method.

How to specify query string parametersIf you want to send data to the server when the client connects, you can add query string parameters to theconnection object. The following examples show how to set a query string parameter in client code.

Set a query string value before calling the start method ﴾with the generated proxy﴿

$.connection.hub.qs = { 'version' : '1.0' };

Set a query string value before calling the start method ﴾without the generated proxy﴿

var connection = $.hubConnection();connection.qs = { 'version' : '1.0' };

The following example shows how to read a query string parameter in server code.

public class ContosoChatHub : Hub{    public override Task OnConnected()    {        var version = Context.QueryString['version'];        if (version != '1.0')        {            Clients.Caller.notifyWrongVersion();        }        return base.OnConnected();    }}

How to specify the transport method

StackOverflow thread ﴾http://stackoverflow.com/questions/13573397/siganlr‐ie9‐cross‐domain‐request‐dont‐work﴿ .

For information about using cross‐domain connections with Chrome, see thisStackOverflow thread ﴾http://stackoverflow.com/questions/15467373/signalr‐1‐0‐1‐cross‐domain‐request‐cors‐with‐chrome﴿ .

The sample code uses the default "/signalr" URL to connect to your SignalR service. Forinformation about how to specify a different base URL, see ASP.NET SignalR Hubs APIGuide ‐ Server ‐ The /signalr URL ﴾/signalr/overview/signalr‐20/hubs‐api/hubs‐api‐guide‐server#signalrurl﴿ .

Page 10: ASP.net SignalR Hubs API Guide - JavaScript Client _ the ASP

8/10/2015 ASP.NET SignalR Hubs API Guide ­ JavaScript Client | The ASP.NET Site

http://www.asp.net/signalr/overview/guide­to­the­api/hubs­api­guide­javascript­client 10/19

As part of the process of connecting, a SignalR client normally negotiates with the server to determine the besttransport that is supported by both server and client. If you already know which transport you want to use, you canbypass this negotiation process by specifying the transport method when you call the start method.

Client code that specifies the transport method ﴾with the generated proxy﴿

$.connection.hub.start( { transport: 'longPolling' });

Client code that specifies the transport method ﴾without the generated proxy﴿

var connection = $.hubConnection();connection.start({ transport: 'longPolling' });

As an alternative, you can specify multiple transport methods in the order in which you want SignalR to try them:

Client code that specifies a custom transport fallback scheme ﴾with the generated proxy﴿

$.connection.hub.start( { transport: ['webSockets', 'longPolling'] });

Client code that specifies a custom transport fallback scheme ﴾without the generated proxy﴿

var connection = $.hubConnection();connection.start({ transport: ['webSockets', 'longPolling'] });

You can use the following values for specifying the transport method:

"webSockets"

"foreverFrame"

"serverSentEvents"

"longPolling"

The following examples show how to find out which transport method is being used by a connectiion.

Client code that displays the transport method used by a connection ﴾with the generated proxy﴿

$.connection.hub.start().done(function () {    console.log("Connected, transport = " + $.connection.hub.transport.name);});

Client code that displays the transport method used by a connection ﴾without the generated proxy﴿

var connection = $.hubConnection();connection.hub.start().done(function () {

Page 11: ASP.net SignalR Hubs API Guide - JavaScript Client _ the ASP

8/10/2015 ASP.NET SignalR Hubs API Guide ­ JavaScript Client | The ASP.NET Site

http://www.asp.net/signalr/overview/guide­to­the­api/hubs­api­guide­javascript­client 11/19

    console.log("Connected, transport = " + connection.transport.name);});

For information about how to check the transport method in server code, see ASP.NET SignalR Hubs API Guide ‐Server ‐ How to get information about the client from the Context property ﴾/signalr/overview/signalr‐20/hubs‐api/hubs‐api‐guide‐server#contextproperty﴿ . For more information about transports and fallbacks, see Introductionto SignalR ‐ Transports and Fallbacks ﴾/signalr/overview/signalr‐20/getting‐started‐with‐signalr‐20/introduction‐to‐signalr#transports﴿ .

How to get a proxy for a Hub classEach connection object that you create encapsulates information about a connection to a SignalR service thatcontains one or more Hub classes. To communicate with a Hub class, you use a proxy object which you createyourself ﴾if you're not using the generated proxy﴿ or which is generated for you.

On the client the proxy name is a camel‐cased version of the Hub class name. SignalR automatically makes thischange so that JavaScript code can conform to JavaScript conventions.

Hub class on server

public class ContosoChatHub : Hub

Get a reference to the generated client proxy for the Hub

var myHubProxy = $.connection.contosoChatHub

Create client proxy for the Hub class ﴾without generated proxy﴿

var contosoChatHubProxy = connection.createHubProxy('contosoChatHub');

If you decorate your Hub class with a HubName attribute, use the exact name without changing case.

Hub class on server with HubName attribute

[HubName("ContosoChatHub")]public class ChatHub : Hub

Get a reference to the generated client proxy for the Hub

var contosoChatHubProxy = $.connection.ContosoChatHub

Create client proxy for the Hub class ﴾without generated proxy﴿

Page 12: ASP.net SignalR Hubs API Guide - JavaScript Client _ the ASP

8/10/2015 ASP.NET SignalR Hubs API Guide ­ JavaScript Client | The ASP.NET Site

http://www.asp.net/signalr/overview/guide­to­the­api/hubs­api­guide­javascript­client 12/19

var contosoChatHubProxy = connection.createHubProxy('ContosoChatHub');

How to define methods on the client that the server can callTo define a method that the server can call from a Hub, add an event handler to the Hub proxy by using the clientproperty of the generated proxy, or call the on method if you aren't using the generated proxy. The parameters canbe complex objects.

Add the event handler before you call the start method to establish the connection. ﴾If you want to add eventhandlers after calling the start method, see the note in How to establish a connection ﴾#establishconnection﴿earlier in this document, and use the syntax shown for defining a method without using the generated proxy.﴿

Method name matching is case‐insensitive. For example, Clients.All.addContosoChatMessageToPage on theserver will execute AddContosoChatMessageToPage, addContosoChatMessageToPage, oraddcontosochatmessagetopage on the client.

Define method on client ﴾with the generated proxy﴿

var contosoChatHubProxy = $.connection.contosoChatHub;contosoChatHubProxy.client.addContosoChatMessageToPage = function (userName, message) {    console.log(userName + ' ' + message);};$.connection.hub.start()    .done(function(){ console.log('Now connected, connection ID=' + $.connection.hub.id); })    .fail(function(){ console.log('Could not Connect!'); });});

Alternate way to define method on client ﴾with the generated proxy﴿

$.extend(contosoChatHubProxy.client, {    addContosoChatMessageToPage: function(userName, message) {    console.log(userName + ' ' + message);    };});

Define method on client ﴾without the generated proxy, or when adding after calling the start method﴿

var connection = $.hubConnection();var contosoChatHubProxy = connection.createHubProxy('contosoChatHub');contosoChatHubProxy.on('addContosoChatMessageToPage', function(userName, message) {    console.log(userName + ' ' + message);});connection.start()    .done(function(){ console.log('Now connected, connection ID=' + connection.id); })    .fail(function(){ console.log('Could not connect'); });

Page 13: ASP.net SignalR Hubs API Guide - JavaScript Client _ the ASP

8/10/2015 ASP.NET SignalR Hubs API Guide ­ JavaScript Client | The ASP.NET Site

http://www.asp.net/signalr/overview/guide­to­the­api/hubs­api­guide­javascript­client 13/19

Server code that calls the client method

public class ContosoChatHub : Hub{    public void NewContosoChatMessage(string name, string message)    {        Clients.All.addContosoChatMessageToPage(name, message);    }}

The following examples include a complex object as a method parameter.

Define method on client that takes a complex object ﴾with the generated proxy﴿

var contosoChatHubProxy = $.connection.contosoChatHub;contosoChatHubProxy.client.addMessageToPage = function (message) {    console.log(message.UserName + ' ' + message.Message);});

Define method on client that takes a complex object ﴾without the generated proxy﴿

var connection = $.hubConnection();var contosoChatHubProxy = connection.createHubProxy('contosoChatHub');chatHubProxy.on('addMessageToPage', function (message) {    console.log(message.UserName + ' ' + message.Message);});

Server code that defines the complex object

public class ContosoChatMessage{    public string UserName { get; set; }    public string Message { get; set; }}

Server code that calls the client method using a complex object

public void SendMessage(string name, string message){    Clients.All.addContosoChatMessageToPage(new ContosoChatMessage() { UserName = name, Message = message });}

How to call server methods from the client

Page 14: ASP.net SignalR Hubs API Guide - JavaScript Client _ the ASP

8/10/2015 ASP.NET SignalR Hubs API Guide ­ JavaScript Client | The ASP.NET Site

http://www.asp.net/signalr/overview/guide­to­the­api/hubs­api­guide­javascript­client 14/19

To call a server method from the client, use the server property of the generated proxy or the invoke method onthe Hub proxy if you aren't using the generated proxy. The return value or parameters can be complex objects.

Pass in a camel‐case version of the method name on the Hub. SignalR automatically makes this change so thatJavaScript code can conform to JavaScript conventions.

The following examples show how to call a server method that doesn't have a return value and how to call a servermethod that does have a return value.

Server method with no HubMethodName attribute

public class ContosoChatHub : Hub{    public void NewContosoChatMessage(ChatMessage message)    {        Clients.All.addContosoChatMessageToPage(message);    }}

Server code that defines the complex object passed in a parameter

public class ChatMessage{    public string UserName { get; set; }    public string Message { get; set; }}

Client code that invokes the server method ﴾with the generated proxy﴿

contosoChatHubProxy.server.newContosoChatMessage({ UserName: userName, Message: message}).done(function () {        console.log ('Invocation of NewContosoChatMessage succeeded');    }).fail(function (error) {        console.log('Invocation of NewContosoChatMessage failed. Error: ' + error);    });

Client code that invokes the server method ﴾without the generated proxy﴿

contosoChatHubProxy.invoke('newContosoChatMessage', { UserName: userName, Message: message}).done(function () {        console.log ('Invocation of NewContosoChatMessage succeeded');    }).fail(function (error) {        console.log('Invocation of NewContosoChatMessage failed. Error: ' + error);    });

Page 15: ASP.net SignalR Hubs API Guide - JavaScript Client _ the ASP

8/10/2015 ASP.NET SignalR Hubs API Guide ­ JavaScript Client | The ASP.NET Site

http://www.asp.net/signalr/overview/guide­to­the­api/hubs­api­guide­javascript­client 15/19

If you decorated the Hub method with a HubMethodName attribute, use that name without changing case.

Server method with a HubMethodName attribute

public class ContosoChatHub : Hub{    [HubMethodName("NewContosoChatMessage")]    public void NewContosoChatMessage(string name, string message)    {        Clients.All.addContosoChatMessageToPage(name, message);    }}

Client code that invokes the server method ﴾with the generated proxy﴿

contosoChatHubProxy.server.NewContosoChatMessage(userName, message).done(function () {        console.log ('Invocation of NewContosoChatMessage succeeded');    }).fail(function (error) {        console.log('Invocation of NewContosoChatMessage failed. Error: ' + error);    });

Client code that invokes the server method ﴾without the generated proxy﴿

contosoChatHubProxy.invoke('NewContosoChatMessage', userName, message).done(function () {        console.log ('Invocation of NewContosoChatMessage succeeded');    }).fail(function (error) {        console.log('Invocation of NewContosoChatMessage failed. Error: ' + error);    });

The preceding examples show how to call a server method that has no return value. The following examples showhow to call a server method that has a return value.

Server code for a method that has a return value

public class StockTickerHub : Hub{    public IEnumerable<Stock> GetAllStocks()    {        return _stockTicker.GetAllStocks();    }}

The Stock class used for the return value

public class Stock

Page 16: ASP.net SignalR Hubs API Guide - JavaScript Client _ the ASP

8/10/2015 ASP.NET SignalR Hubs API Guide ­ JavaScript Client | The ASP.NET Site

http://www.asp.net/signalr/overview/guide­to­the­api/hubs­api­guide­javascript­client 16/19

{    public string Symbol { get; set; }    public decimal Price { get; set; }}

Client code that invokes the server method ﴾with the generated proxy﴿

function init() {    return stockTickerProxy.server.getAllStocks().done(function (stocks) {        $.each(stocks, function () {            var stock = this;            console.log("Symbol=" + stock.Symbol + " Price=" + stock.Price);        });    }).fail(function (error) {        console.log('Error: ' + error);    });}

Client code that invokes the server method ﴾without the generated proxy﴿

function init() {    return stockTickerProxy.invoke('getAllStocks').done(function (stocks) {        $.each(stocks, function () {            var stock = this;            console.log("Symbol=" + stock.Symbol + " Price=" + stock.Price);        });    }).fail(function (error) {        console.log('Error: ' + error);    });}

How to handle connection lifetime eventsSignalR provides the following connection lifetime events that you can handle:

starting: Raised before any data is sent over the connection.

received: Raised when any data is received on the connection. Provides the received data.

connectionSlow: Raised when the client detects a slow or frequently dropping connection.

reconnecting: Raised when the underlying transport begins reconnecting.

reconnected: Raised when the underlying transport has reconnected.

stateChanged: Raised when the connection state changes. Provides the old state and the new state﴾Connecting, Connected, Reconnecting, or Disconnected﴿.

disconnected: Raised when the connection has disconnected.

For example, if you want to display warning messages when there are connection problems that might cause

Page 17: ASP.net SignalR Hubs API Guide - JavaScript Client _ the ASP

8/10/2015 ASP.NET SignalR Hubs API Guide ­ JavaScript Client | The ASP.NET Site

http://www.asp.net/signalr/overview/guide­to­the­api/hubs­api­guide­javascript­client 17/19

noticeable delays, handle the connectionSlow event.

Handle the connectionSlow event ﴾with the generated proxy﴿

$.connection.hub.connectionSlow(function () {    console.log('We are currently experiencing difficulties with the connection.')});

Handle the connectionSlow event ﴾without the generated proxy﴿

var connection = $.hubConnection();connection.connectionSlow(function () {    console.log('We are currently experiencing difficulties with the connection.')});

For more information, see Understanding and Handling Connection Lifetime Events in SignalR﴾/signalr/overview/signalr‐20/hubs‐api/handling‐connection‐lifetime‐events﴿ .

How to handle errorsThe SignalR JavaScript client provides an error event that you can add a handler for. You can also use the failmethod to add a handler for errors that result from a server method invocation.

If you don't explicitly enable detailed error messages on the server, the exception object that SignalR returns after anerror contains minimal information about the error. For example, if a call to newContosoChatMessage fails, the errormessage in the error object contains "There was an error invoking Hub method'contosoChatHub.newContosoChatMessage'." Sending detailed error messages to clients in production is notrecommended for security reasons, but if you want to enable detailed error messages for troubleshooting purposes,use the following code on the server.

var hubConfiguration = new HubConfiguration (http://msdn.microsoft.com/en‐us/library/microsoft.aspnet.signalr.hubconfiguration(v=vs.111).aspx) ();hubConfiguration.EnableDetailedErrors = true;app.MapSignalR(hubConfiguration);

The following example shows how to add a handler for the error event.

Add an error handler ﴾with the generated proxy﴿

$.connection.hub.error(function (error) {    console.log('SignalR error: ' + error)});

Add an error handler ﴾without the generated proxy﴿

Page 18: ASP.net SignalR Hubs API Guide - JavaScript Client _ the ASP

8/10/2015 ASP.NET SignalR Hubs API Guide ­ JavaScript Client | The ASP.NET Site

http://www.asp.net/signalr/overview/guide­to­the­api/hubs­api­guide­javascript­client 18/19

var connection = $.hubConnection();connection.error(function (error) {    console.log('SignalR error: ' + error)});

The following example shows how to handle an error from a method invocation.

Handle an error from a method invocation ﴾with the generated proxy﴿

contosoChatHubProxy.newContosoChatMessage(userName, message)    .fail(function(error) {         console.log( 'newContosoChatMessage error: ' + error)     });

Handle an error from a method invocation ﴾without the generated proxy﴿

contosoChatHubProxy.invoke('newContosoChatMessage', userName, message)    .fail(function(error) {         console.log( 'newContosoChatMessage error: ' + error)     });

If a method invocation fails, the error event is also raised, so your code in the error method handler and in the.fail method callback would execute.

How to enable client‐side loggingTo enable client‐side logging on a connection, set the logging property on the connection object before you call thestart method to establish the connection.

Enable logging ﴾with the generated proxy﴿

$.connection.hub.logging = true;$.connection.hub.start();

Enable logging ﴾without the generated proxy﴿

var connection = $.hubConnection();connection.logging = true;connection.start();

To see the logs, open your browser's developer tools and go to the Console tab. For a tutorial that shows step‐by‐step instructions and screen shots that show how to do this, see Server Broadcast with ASP.NET Signalr ‐ EnableLogging ﴾/signalr/overview/signalr‐20/getting‐started‐with‐signalr‐20/tutorial‐server‐broadcast‐with‐signalr‐20#enablelogging﴿ .

Page 19: ASP.net SignalR Hubs API Guide - JavaScript Client _ the ASP

8/10/2015 ASP.NET SignalR Hubs API Guide ­ JavaScript Client | The ASP.NET Site

http://www.asp.net/signalr/overview/guide­to­the­api/hubs­api­guide­javascript­client 19/19

This article was originally created on June 10, 2014

Author Information

Tom Dykstra – Tom Dykstra is a Senior Programming Writer on Microsoft's Web Platform &Tools Content Team...

Patrick Fletcher – Patrick Fletcher is a former programmer‐writer on the ASP.NET team.

Comments ﴾10﴿

This site is managed for Microsoft by Neudesic, LLC. | © 2015 Microsoft. All rights reserved.