Signalr Hubs API Guide - .Net Client (C#) - The ASP
Signalr Hubs API Guide - .Net Client (C#) - The ASP
Signalr Hubs API Guide - .Net Client (C#) - The ASP
ASP.NETSignalRHubsAPIGuide.NETClient(C#)|TheASP.NETSite
This document provides an introduction to using the Hubs API for SignalR version 2 in .NET clients, such as
Windows Store WinRT, WPF, Silverlight, and console 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, or for a tutorial that shows how to build a complete SignalR application, see SignalR
Getting Started /signalr/overview/signalr20/gettingstartedwithsignalr20 .
1/14
8/10/2015
ASP.NETSignalRHubsAPIGuide.NETClient(C#)|TheASP.NETSite
Links to API Reference topics are to the .NET 4.5 version of the API. If you're using .NET 4, see the .NET 4 version of
the API topics http://msdn.microsoft.com/enus/library/jj891075v=vs.100.aspx .
Client setup
Install the Microsoft.AspNet.SignalR.Client http://nuget.org/packages/Microsoft.AspNet.SignalR.Client NuGet
package not the Microsoft.AspNet.SignalR http://nuget.org/packages/microsoft.aspnet.signalr package. This
package supports WinRT, Silverlight, WPF, console application, and Windows Phone clients, for both .NET 4 and .NET
4.5.
If the version of SignalR that you have on the client is different from the version that you have on the server, SignalR
is often able to adapt to the difference. For example, a server running SignalR version 2 will support clients that have
1.1.x installed as well as clients that have version 2 installed. If the difference between the version on the server and
the version on the client is too great, or if the client is newer than the server, SignalR throws an
InvalidOperationException exception when the client tries to establish a connection. The error message is "You
areusingaversionoftheclientthatisn'tcompatiblewiththeserver.ClientversionX.X,
serverversionX.X".
2/14
8/10/2015
ASP.NETSignalRHubsAPIGuide.NETClient(C#)|TheASP.NETSite
for{0}newprice{1}",stock.Symbol,stock.Price));
awaithubConnection.Start();
Note: For JavaScript clients you have to register at least one event handler before calling the
Start method to establish the connection. This is not necessary for .NET clients. For JavaScript
clients, the generated proxy code automatically creates proxies for all Hubs that exist on the
server, and registering a handler is how you indicate which Hubs your client intends to use. But
for a .NET client you create Hub proxies manually, so SignalR assumes that you will be using any
Hub that you create a proxy for.
The sample code uses the default "/signalr" URL to connect to your SignalR service. For information about how to
specify a different base URL, see ASP.NET SignalR Hubs API Guide Server The /signalr URL
/signalr/overview/signalr20/hubsapi/hubsapiguideserver#signalrurl .
The Start method executes asynchronously. To make sure that subsequent lines of code don't execute until after the
connection is established, use await in an ASP.NET 4.5 asynchronous method or .Wait() in a synchronous method.
Don't use .Wait() in a WinRT client.
awaitconnection.Start();
connection.Start().Wait();
http://www.asp.net/signalr/overview/guidetotheapi/hubsapiguidenetclient
3/14
8/10/2015
ASP.NETSignalRHubsAPIGuide.NETClient(C#)|TheASP.NETSite
varhubConnection=newHubConnection("http://www.contoso.com/");
IHubProxystockTickerHubProxy=hubConnection.CreateHubProxy("StockTickerHub");
stockTickerHubProxy.On<Stock>("UpdateStockPrice",stock=>Console.WriteLine("Stockupdate
for{0}newprice{1}",stock.Symbol,stock.Price));
ServicePointManager.DefaultConnectionLimit=10;
awaithubConnection.Start();
The following example shows how to read a query string parameter in server code.
publicclassStockTickerHub:Hub
{
publicoverrideTaskOnConnected()
{
varversion=Context.QueryString["contosochatversion"];
if(version!="1.0")
{
Clients.Caller.notifyWrongVersion();
}
returnbase.OnConnected();
}
}
http://www.asp.net/signalr/overview/guidetotheapi/hubsapiguidenetclient
4/14
8/10/2015
ASP.NETSignalRHubsAPIGuide.NETClient(C#)|TheASP.NETSite
ServerSentEventsTransport http://msdn.microsoft.com/en
us/library/microsoft.aspnet.signalr.client.transports.serversenteventstransportv=vs.111.aspx
WebSocketTransport http://msdn.microsoft.com/en
us/library/microsoft.aspnet.signalr.client.transports.websockettransportv=vs.111.aspx Available only when both
transport that is supported by both the client and the server. This is the default transport. Passing this in to the
Start method has the same effect as not passing in anything.
The ForeverFrame transport is not included in this list because it is used only by browsers.
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 .
5/14
8/10/2015
ASP.NETSignalRHubsAPIGuide.NETClient(C#)|TheASP.NETSite
In order to define methods on the client that a Hub can call from the server, and to invoke methods on a Hub at the
server, create a proxy for the Hub by calling CreateHubProxy on the connection object. The string you pass in to
CreateHubProxy is the name of your Hub class, or the name specified by the HubName attribute if one was used on
the server. Name matching is caseinsensitive.
Hub class on server
publicclassStockTickerHub:Hub
If you decorate your Hub class with a HubName attribute, use that name.
Hub class on server
[HubName("stockTicker")]
publicclassStockTickerHub:Hub
The proxy object is threadsafe. In fact, if you call HubConnection.CreateHubProxy multiple times with the same
hubName, you get the same cached IHubProxy object.
How to define methods on the client that the server can call
To define a method that the server can call, use the proxy's On method to register an event handler.
Method name matching is caseinsensitive. For example, Clients.All.UpdateStockPrice on the server will
execute updateStockPrice, updatestockprice, or UpdateStockPrice on the client.
Different client platforms have different requirements for how you write method code to update the UI. The examples
shown are for WinRT Windows Store .NET clients. WPF, Silverlight, and console application examples are provided in
a separate section later in this topic #wpfsl .
http://www.asp.net/signalr/overview/guidetotheapi/hubsapiguidenetclient
6/14
8/10/2015
ASP.NETSignalRHubsAPIGuide.NETClient(C#)|TheASP.NETSite
WinRT Client code for method called from server without parameters see WPF and Silverlight examples later
in this topic #wpfsl
varhubConnection=newHubConnection("http://www.contoso.com/");
IHubProxystockTickerHubProxy=hubConnection.CreateHubProxy("StockTickerHub");
stockTickerHub.On("notify",()=>
//ContextisareferencetoSynchronizationContext.Current
Context.Post(delegate
{
textBox.Text+="Notified!\n";
},null)
);
awaithubConnection.Start();
7/14
8/10/2015
ASP.NETSignalRHubsAPIGuide.NETClient(C#)|TheASP.NETSite
WinRT Client code for a method called from server with a parameter see WPF and Silverlight examples later
in this topic #wpfsl
stockTickerHubProxy.On<Stock>("UpdateStockPrice",stock=>
//ContextisareferencetoSynchronizationContext.Current
Context.Post(delegate
{
textBox.Text+=string.Format("Stockupdatefor{0}newprice{1}\n",stock.Symbol,
stock.Price);
},null)
);
WinRT Client code for a method called from server with a parameter, using a dynamic object for the
parameter see WPF and Silverlight examples later in this topic #wpfsl
stockTickerHubProxy.On("UpdateStockPrice",stock=>
//ContextisareferencetoSynchronizationContext.Current
Context.Post(delegate
{
textBox.Text+=string.Format("Stockupdatefor{0}newprice{1}\n",stock.Symbol,
stock.Price);
},null)
);
http://www.asp.net/signalr/overview/guidetotheapi/hubsapiguidenetclient
8/14
8/10/2015
ASP.NETSignalRHubsAPIGuide.NETClient(C#)|TheASP.NETSite
If the server method has a return value, specify the return type as the generic type of the Invoke method.
Server code for a method that has a return value and takes a complex type parameter
publicIEnumerable<Stock>AddStock(Stockstock)
{
_stockTicker.AddStock(stock);
http://www.asp.net/signalr/overview/guidetotheapi/hubsapiguidenetclient
9/14
8/10/2015
ASP.NETSignalRHubsAPIGuide.NETClient(C#)|TheASP.NETSite
return_stockTicker.GetAllStocks();
}
The Stock class used for the parameter and return value
publicclassStock
{
publicstringSymbol{get;set;}
publicdecimalPrice{get;set;}
}
Client code calling a method that has a return value and takes a complex type parameter, in an ASP.NET 4.5
async method
varstocks=awaitstockTickerHub.Invoke<IEnumerable<Stock>>("AddStock",newStock(){
Symbol="MSFT"});
foreach(Stockstockinstocks)
{
textBox.Text+=string.Format("Symbol:{0}price:{1}\n",stock.Symbol,stock.Price);
}
Client code calling a method that has a return value and takes a complex type parameter, in a synchronous
method
varstocks=stockTickerHub.Invoke<IEnumerable<Stock>>("AddStock",newStock(){Symbol=
"MSFT"}).Result;
foreach(Stockstockinstocks)
{
textBox.Text+=string.Format("Symbol:{0}price:{1}\n",stock.Symbol,stock.Price);
}
The Invoke method executes asynchronously and returns a Task object. If you don't specify await or .Wait(), the
next line of code will execute before the method that you invoke has finished executing.
10/14
8/10/2015
ASP.NETSignalRHubsAPIGuide.NETClient(C#)|TheASP.NETSite
us/library/microsoft.aspnet.signalr.client.connectionstatev=vs.111.aspx .
For more information, see Understanding and Handling Connection Lifetime Events in SignalR
/signalr/overview/signalr20/hubsapi/handlingconnectionlifetimeevents .
To handle errors that SignalR raises, you can add a handler for the Error event on the connection object.
hubConnection.Error+=ex=>Console.WriteLine("SignalRerror:{0}",ex.Message);
To handle errors from method invocations, wrap the code in a trycatch block.
try
{
IEnumerable<Stock>stocks=awaitstockTickerHub.Invoke<IEnumerable<Stock>>
("GetAllStocks");
foreach(Stockstockinstocks)
{
Console.WriteLine("Symbol:{0}price:{1}",stock.Symbol,stock.Price);
}
}
catch(Exceptionex)
{
Console.WriteLine("ErrorinvokingGetAllStocks:{0}",ex.Message);
}
http://www.asp.net/signalr/overview/guidetotheapi/hubsapiguidenetclient
11/14
8/10/2015
ASP.NETSignalRHubsAPIGuide.NETClient(C#)|TheASP.NETSite
WPF, Silverlight, and console application code samples for client methods
that the server can call
The code samples shown earlier for defining client methods that the server can call apply to WinRT clients. The
following samples show the equivalent code for WPF, Silverlight, and console application clients.
Silverlight client code for method called from server without parameters
stockTickerHub.On<Stock>("notify",()=>
//ContextisareferencetoSynchronizationContext.Current
Context.Post(delegate
{
textBox.Text+="Notified!";
},null)
);
Console application client code for method called from server without parameters
stockTickerHubProxyProxy.On("Notify",()=>Console.WriteLine("Notified!"));
12/14
8/10/2015
ASP.NETSignalRHubsAPIGuide.NETClient(C#)|TheASP.NETSite
stockTickerHubProxy.On<Stock>("UpdateStockPrice",stock=>
Dispatcher.InvokeAsync(()=>
{
textBox.Text+=string.Format("Stockupdatefor{0}newprice{1}\n",
stock.Symbol,stock.Price);
})
);
Silverlight client code for a method called from server with a parameter
stockTickerHubProxy.On<Stock>("UpdateStockPrice",stock=>
//ContextisareferencetoSynchronizationContext.Current
Context.Post(delegate
{
textBox.Text+=string.Format("Stockupdatefor{0}newprice{1}\n",stock.Symbol,
stock.Price);
},null)
);
Console application client code for a method called from server with a parameter
stockTickerHubProxy.On<Stock>("UpdateStockPrice",stock=>
Console.WriteLine("Symbol{0}Price{1}",stock.Symbol,stock.Price));
Silverlight client code for a method called from server with a parameter, using a dynamic object for the
parameter
stockTickerHubProxy.On("UpdateStockPrice",stock=>
//ContextisareferencetoSynchronizationContext.Current
Context.Post(delegate
{
textBox.Text+=string.Format("Stockupdatefor{0}newprice{1}\n",stock.Symbol,
stock.Price);
http://www.asp.net/signalr/overview/guidetotheapi/hubsapiguidenetclient
13/14
8/10/2015
ASP.NETSignalRHubsAPIGuide.NETClient(C#)|TheASP.NETSite
},null)
);
Console application client code for a method called from server with a parameter, using a dynamic object for
the parameter
stockTickerHubProxy.On("UpdateStockPrice",stock=>
Console.WriteLine("Symbol{0}Price{1}",stock.Symbol,stock.Price));
Author Information
Tom DykstraTom Dykstra is a Senior Programming Writer on Microsoft's Web Platform &
Tools Content Team...
Comments 9
This site is managed for Microsoft by Neudesic, LLC. | 2015 Microsoft. All rights reserved.
http://www.asp.net/signalr/overview/guidetotheapi/hubsapiguidenetclient
14/14