ASP.NETSignalRHubsAPIGuideJavaScriptClient|TheASP.NETSite
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 clienttoserver plumbing for you.
SignalR also offers a lowerlevel API called Persistent Connections. For an introduction to SignalR, Hubs, and
Persistent Connections, see Introduction to SignalR /signalr/overview/signalr20/gettingstartedwithsignalr
20/introductiontosignalr .
1/19
8/10/2015
ASP.NETSignalRHubsAPIGuideJavaScriptClient|TheASP.NETSite
The following code examples show what JavaScript code looks like for invoking the NewContosoChatMessage
method on the server and receiving invocations of the addContosoChatMessageToPage method from the server.
With the generated proxy
varcontosoChatHubProxy=$.connection.contosoChatHub;
contosoChatHubProxy.client.addContosoChatMessageToPage=function(name,message){
console.log(name+''+message);
};
$.connection.hub.start().done(function(){
//WireupSendbuttontocallNewContosoChatMessageontheserver.
$('#newContosoChatMessage').click(function(){
contosoChatHubProxy.server.newContosoChatMessage($('#displayname').val(),
$('#message').val());
$('#message').val('').focus();
http://www.asp.net/signalr/overview/guidetotheapi/hubsapiguidejavascriptclient
2/19
8/10/2015
ASP.NETSignalRHubsAPIGuideJavaScriptClient|TheASP.NETSite
});
});
Client setup
A JavaScript client requires references to jQuery and the SignalR core JavaScript file. The jQuery version must be 1.6.4
or 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 a
reference to the SignalR generated proxy JavaScript file. The following example shows what the references might look
like in an HTML page that uses the generated proxy.
<scriptsrc="Scripts/jquery1.10.2.min.js"></script>
<scriptsrc="Scripts/jquery.signalR2.1.0.min.js"></script>
<scriptsrc="signalr/hubs"></script>
These references must be included in this order: jQuery first, SignalR core after that, and SignalR proxies last.
Note: For Windows 8 Windows Store JavaScript clients, use the physical proxy file instead of
http://www.asp.net/signalr/overview/guidetotheapi/hubsapiguidejavascriptclient
3/19
8/10/2015
ASP.NETSignalRHubsAPIGuideJavaScriptClient|TheASP.NETSite
the dynamically generated one. For more information, see How to create a physical file for the
SignalR generated proxy #manualproxy later in this topic.
In an ASP.NET MVC 4 or 5 Razor view, use the tilde to refer to the application root in your proxy file reference:
<scriptsrc="~/signalr/hubs"></script>
For more information about using SignalR in MVC 5, see Getting Started with SignalR and MVC 5
/signalr/overview/signalr20/gettingstartedwithsignalr20/tutorialgettingstartedwithsignalr20andmvc5 .
In an ASP.NET MVC 3 Razor view, use Url.Content for your proxy file reference:
<scriptsrc="@Url.Content("~/signalr/hubs")"></script>
In an ASP.NET Web Forms application, use ResolveClientUrl for your proxies file reference or register it via the
ScriptManager using an app root relative path starting with a tilde:
<scriptsrc='<%: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 in
Visual Studio using IIS Express but will fail with a 404 error when you deploy to full IIS. For more information, see
Resolving References to RootLevel Resources in Web Servers in Visual Studio for ASP.NET Web Projects
http://msdn.microsoft.com/enus/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, doubleclick hubs. If you are not using Visual Studio 2012 or 2013 and Internet
Explorer, 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 to
http://localhost:56699/SignalR/hubs in your browser.
4/19
8/10/2015
ASP.NETSignalRHubsAPIGuideJavaScriptClient|TheASP.NETSite
2. Open a command prompt and browse to the tools folder that contains the SignalR.exe file. The tools folder is at
the following location:
[yoursolutionfolder]\packages\Microsoft.AspNet.SignalR.Utils.2.1.0\tools
3. Enter the following command:
signalrghp/path:[pathtothe.dllthatcontainsyourHubclass]
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, and
add a reference to it in place of the "signalr/hubs" reference.
The sample code uses the default "/signalr" URL to connect to your SignalR service. For information about how to
http://www.asp.net/signalr/overview/guidetotheapi/hubsapiguidejavascriptclient
5/19
8/10/2015
ASP.NETSignalRHubsAPIGuideJavaScriptClient|TheASP.NETSite
specify a different base URL, see ASP.NET SignalR Hubs API Guide Server The /signalr URL
/signalr/overview/signalr20/hubsapi/hubsapiguideserver#signalrurl .
Note: Normally you register event handlers before calling the start method to establish the
connection. If you want to register some event handlers after establishing the connection, you
can do that, but you must register at least one of your event handlers before calling the start
method. One reason for this is that there can be many Hubs in an application, but you wouldn't
want to trigger the OnConnected event on every Hub if you are only going to use to one of
them. When the connection is established, the presence of a client method on a Hub's proxy is
what tells SignalR to trigger the OnConnected event. If you don't register any event handlers
before calling the start method, you will be able to invoke methods on the Hub, but the Hub's
OnConnected method won't be called and no client methods will be invoked from the server.
When you're using the generated proxy, you can do anything with $.connection.hub that you can do with a
connection object when you're not using the generated proxy.
http://www.asp.net/signalr/overview/guidetotheapi/hubsapiguidejavascriptclient
6/19
8/10/2015
ASP.NETSignalRHubsAPIGuideJavaScriptClient|TheASP.NETSite
Calling UseCors
The following code snippet demonstrates how to implement crossdomain connections in SignalR 2.
Implementing crossdomain requests in SignalR 2
The following code demonstrates how to enable CORS or JSONP in a SignalR 2 project. This code sample uses Map
and RunSignalR instead of MapSignalR, so that the CORS middleware runs only for the SignalR requests that require
CORS support rather than for all traffic at the path specified in MapSignalR. Map can also be used for any other
middleware that needs to run for a specific URL prefix, rather than for the entire application.
usingMicrosoft.AspNet.SignalR;
usingMicrosoft.Owin.Cors;
http://www.asp.net/signalr/overview/guidetotheapi/hubsapiguidejavascriptclient
7/19
8/10/2015
ASP.NETSignalRHubsAPIGuideJavaScriptClient|TheASP.NETSite
usingOwin;
namespaceMyWebApplication
{
publicclassStartup
{
publicvoidConfiguration(IAppBuilderapp)
{
//Branchthepipelinehereforrequeststhatstartwith"/signalr"
app.Map("/signalr",map=>
{
//SetuptheCORSmiddlewaretorunbeforeSignalR.
//Bydefaultthiswillallowallorigins.Youcan
//configurethesetoforiginsand/orhttpverbsby
//providingacorsoptionswithadifferentpolicy.
map.UseCors(CorsOptions.AllowAll);
varhubConfiguration=newHubConfiguration
{
//YoucanenableJSONPbyuncommentinglinebelow.
//JSONPrequestsareinsecurebutsomeolderbrowsers(andsome
//versionsofIE)requireJSONPtoworkcrossdomain
//EnableJSONP=true
};
//RuntheSignalRpipeline.We'renotusingMapSignalR
//sincethisbranchalreadyrunsunderthe"/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 JSONP
because 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't
enabled crossdomain connections on the server.
For information about using crossdomain connections with Internet Explorer 9, see this
http://www.asp.net/signalr/overview/guidetotheapi/hubsapiguidejavascriptclient
8/19
8/10/2015
ASP.NETSignalRHubsAPIGuideJavaScriptClient|TheASP.NETSite
Set a query string value before calling the start method without the generated proxy
varconnection=$.hubConnection();
connection.qs={'version':'1.0'};
The following example shows how to read a query string parameter in server code.
publicclassContosoChatHub:Hub
{
publicoverrideTaskOnConnected()
{
varversion=Context.QueryString['version'];
if(version!='1.0')
{
Clients.Caller.notifyWrongVersion();
}
returnbase.OnConnected();
}
}
9/19
8/10/2015
ASP.NETSignalRHubsAPIGuideJavaScriptClient|TheASP.NETSite
As part of the process of connecting, a SignalR client normally negotiates with the server to determine the best
transport that is supported by both server and client. If you already know which transport you want to use, you can
bypass 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
varconnection=$.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
varconnection=$.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
varconnection=$.hubConnection();
connection.hub.start().done(function(){
http://www.asp.net/signalr/overview/guidetotheapi/hubsapiguidejavascriptclient
10/19
8/10/2015
ASP.NETSignalRHubsAPIGuideJavaScriptClient|TheASP.NETSite
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/signalr20/hubs
api/hubsapiguideserver#contextproperty . For more information about transports and fallbacks, see Introduction
to SignalR Transports and Fallbacks /signalr/overview/signalr20/gettingstartedwithsignalr20/introductionto
signalr#transports .
Create client proxy for the Hub class without generated proxy
varcontosoChatHubProxy=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")]
publicclassChatHub:Hub
Create client proxy for the Hub class without generated proxy
http://www.asp.net/signalr/overview/guidetotheapi/hubsapiguidejavascriptclient
11/19
8/10/2015
ASP.NETSignalRHubsAPIGuideJavaScriptClient|TheASP.NETSite
varcontosoChatHubProxy=connection.createHubProxy('ContosoChatHub');
How to define methods on the client that the server can call
To define a method that the server can call from a Hub, add an event handler to the Hub proxy by using the client
property of the generated proxy, or call the on method if you aren't using the generated proxy. The parameters can
be complex objects.
Add the event handler before you call the start method to establish the connection. If you want to add event
handlers 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 caseinsensitive. For example, Clients.All.addContosoChatMessageToPage on the
server will execute AddContosoChatMessageToPage, addContosoChatMessageToPage, or
addcontosochatmessagetopage on the client.
Define method on client with the generated proxy
varcontosoChatHubProxy=$.connection.contosoChatHub;
contosoChatHubProxy.client.addContosoChatMessageToPage=function(userName,message){
console.log(userName+''+message);
};
$.connection.hub.start()
.done(function(){console.log('Nowconnected,connectionID='+$.connection.hub.id);})
.fail(function(){console.log('CouldnotConnect!');});
});
Define method on client without the generated proxy, or when adding after calling the start method
varconnection=$.hubConnection();
varcontosoChatHubProxy=connection.createHubProxy('contosoChatHub');
contosoChatHubProxy.on('addContosoChatMessageToPage',function(userName,message){
console.log(userName+''+message);
});
connection.start()
.done(function(){console.log('Nowconnected,connectionID='+connection.id);})
.fail(function(){console.log('Couldnotconnect');});
http://www.asp.net/signalr/overview/guidetotheapi/hubsapiguidejavascriptclient
12/19
8/10/2015
ASP.NETSignalRHubsAPIGuideJavaScriptClient|TheASP.NETSite
Define method on client that takes a complex object without the generated proxy
varconnection=$.hubConnection();
varcontosoChatHubProxy=connection.createHubProxy('contosoChatHub');
chatHubProxy.on('addMessageToPage',function(message){
console.log(message.UserName+''+message.Message);
});
Server code that calls the client method using a complex object
publicvoidSendMessage(stringname,stringmessage)
{
Clients.All.addContosoChatMessageToPage(newContosoChatMessage(){UserName=name,
Message=message});
}
13/19
8/10/2015
ASP.NETSignalRHubsAPIGuideJavaScriptClient|TheASP.NETSite
To call a server method from the client, use the server property of the generated proxy or the invoke method on
the Hub proxy if you aren't using the generated proxy. The return value or parameters can be complex objects.
Pass in a camelcase version of the method name on the Hub. SignalR automatically makes this change so that
JavaScript 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 server
method that does have a return value.
Server method with no HubMethodName attribute
publicclassContosoChatHub:Hub
{
publicvoidNewContosoChatMessage(ChatMessagemessage)
{
Clients.All.addContosoChatMessageToPage(message);
}
}
Client code that invokes the server method with the generated proxy
contosoChatHubProxy.server.newContosoChatMessage({UserName:userName,Message:
message}).done(function(){
console.log('InvocationofNewContosoChatMessagesucceeded');
}).fail(function(error){
console.log('InvocationofNewContosoChatMessagefailed.Error:'+error);
});
Client code that invokes the server method without the generated proxy
contosoChatHubProxy.invoke('newContosoChatMessage',{UserName:userName,Message:
message}).done(function(){
console.log('InvocationofNewContosoChatMessagesucceeded');
}).fail(function(error){
console.log('InvocationofNewContosoChatMessagefailed.Error:'+error);
});
http://www.asp.net/signalr/overview/guidetotheapi/hubsapiguidejavascriptclient
14/19
8/10/2015
ASP.NETSignalRHubsAPIGuideJavaScriptClient|TheASP.NETSite
If you decorated the Hub method with a HubMethodName attribute, use that name without changing case.
Server method with a HubMethodName attribute
publicclassContosoChatHub:Hub
{
[HubMethodName("NewContosoChatMessage")]
publicvoidNewContosoChatMessage(stringname,stringmessage)
{
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('InvocationofNewContosoChatMessagesucceeded');
}).fail(function(error){
console.log('InvocationofNewContosoChatMessagefailed.Error:'+error);
});
Client code that invokes the server method without the generated proxy
contosoChatHubProxy.invoke('NewContosoChatMessage',userName,message).done(function(){
console.log('InvocationofNewContosoChatMessagesucceeded');
}).fail(function(error){
console.log('InvocationofNewContosoChatMessagefailed.Error:'+error);
});
The preceding examples show how to call a server method that has no return value. The following examples show
how to call a server method that has a return value.
Server code for a method that has a return value
publicclassStockTickerHub:Hub
{
publicIEnumerable<Stock>GetAllStocks()
{
return_stockTicker.GetAllStocks();
}
}
15/19
8/10/2015
ASP.NETSignalRHubsAPIGuideJavaScriptClient|TheASP.NETSite
{
publicstringSymbol{get;set;}
publicdecimalPrice{get;set;}
}
Client code that invokes the server method with the generated proxy
functioninit(){
returnstockTickerProxy.server.getAllStocks().done(function(stocks){
$.each(stocks,function(){
varstock=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
functioninit(){
returnstockTickerProxy.invoke('getAllStocks').done(function(stocks){
$.each(stocks,function(){
varstock=this;
console.log("Symbol="+stock.Symbol+"Price="+stock.Price);
});
}).fail(function(error){
console.log('Error:'+error);
});
}
16/19
8/10/2015
ASP.NETSignalRHubsAPIGuideJavaScriptClient|TheASP.NETSite
For more information, see Understanding and Handling Connection Lifetime Events in SignalR
/signalr/overview/signalr20/hubsapi/handlingconnectionlifetimeevents .
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('SignalRerror:'+error)
});
http://www.asp.net/signalr/overview/guidetotheapi/hubsapiguidejavascriptclient
17/19
8/10/2015
ASP.NETSignalRHubsAPIGuideJavaScriptClient|TheASP.NETSite
varconnection=$.hubConnection();
connection.error(function(error){
console.log('SignalRerror:'+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('newContosoChatMessageerror:'+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.
To see the logs, open your browser's developer tools and go to the Console tab. For a tutorial that shows stepby
step instructions and screen shots that show how to do this, see Server Broadcast with ASP.NET Signalr Enable
Logging /signalr/overview/signalr20/gettingstartedwithsignalr20/tutorialserverbroadcastwithsignalr
20#enablelogging .
http://www.asp.net/signalr/overview/guidetotheapi/hubsapiguidejavascriptclient
18/19
8/10/2015
ASP.NETSignalRHubsAPIGuideJavaScriptClient|TheASP.NETSite
Author Information
Tom DykstraTom Dykstra is a Senior Programming Writer on Microsoft's Web Platform &
Tools Content Team...
Comments 10
This site is managed for Microsoft by Neudesic, LLC. | 2015 Microsoft. All rights reserved.
http://www.asp.net/signalr/overview/guidetotheapi/hubsapiguidejavascriptclient
19/19