|
2 | 2 | uid: Uno.Development.SignalR |
3 | 3 | --- |
4 | 4 |
|
5 | | -# SignalR |
| 5 | +# How to integrate SignalR with an Uno Platform app |
6 | 6 |
|
7 | | -[SignalR](https://learn.microsoft.com/aspnet/core/signalr/introduction?view=aspnetcore-7.0) is an ASP.NET Core library that allows server-side code to be instantly pushed to the client. |
| 7 | +[ASP.NET Core SignalR](https://learn.microsoft.com/aspnet/core/signalr/introduction) is an open-source library that simplifies adding real-time web functionality to apps. It enables server-side code to push content to connected clients instantly using WebSockets, Server-Sent Events, or Long Polling (chosen automatically based on capabilities). |
| 8 | + |
| 9 | +SignalR is a good fit for Uno Platform apps that need: |
| 10 | + |
| 11 | +- Real-time messaging or chat |
| 12 | +- Live dashboards and monitoring |
| 13 | +- Collaborative editing |
| 14 | +- Push notifications from a server |
| 15 | + |
| 16 | +This guide walks you through creating an ASP.NET Core SignalR server and connecting to it from an Uno Platform client app. The SignalR .NET client (`Microsoft.AspNetCore.SignalR.Client`) works on all Uno target platforms — WebAssembly, Desktop (Windows, macOS, Linux via Skia), iOS, and Android. |
8 | 17 |
|
9 | 18 | ## Prerequisites |
10 | 19 |
|
11 | | -- Visual Studio 2019 or higher |
12 | | -- Azure account (to publish SignalR service) |
| 20 | +- [.NET 9.0 SDK](https://dotnet.microsoft.com/download) or later |
| 21 | +- An Uno Platform app (created via `dotnet new unoapp` or the Uno Platform Visual Studio extension) |
| 22 | +- Visual Studio 2022 17.8+, VS Code, or JetBrains Rider |
| 23 | + |
| 24 | +> [!NOTE] |
| 25 | +> An Azure account is **not** required. You can run the SignalR server locally during development. For production hosting options, see [Publish an ASP.NET Core SignalR app to Azure](https://learn.microsoft.com/aspnet/core/signalr/publish-to-azure-web-app) or [Azure SignalR Service](https://learn.microsoft.com/azure/azure-signalr/signalr-overview). |
13 | 26 |
|
14 | | -## Steps |
| 27 | +## Step 1 — Create the SignalR server |
15 | 28 |
|
16 | | -1. Create `ASP.NET Core web application` in Visual Studio and name it `UnoChat.Service`. |
| 29 | +Create a new ASP.NET Core Web API project that will host the SignalR hub: |
17 | 30 |
|
18 | | -  |
| 31 | +```dotnetcli |
| 32 | +dotnet new web -n ChatServer |
| 33 | +cd ChatServer |
| 34 | +``` |
19 | 35 |
|
20 | | -2. Add [SignalR Hub](https://learn.microsoft.com/aspnet/core/tutorials/signalr?view=aspnetcore-7.0&tabs=visual-studio#create-a-signalr-hub) to your `[YourProjectName].Service` project in a `Hubs` folder. |
| 36 | +### Define a SignalR Hub |
21 | 37 |
|
22 | | -3. In your `Startup.cs` file, add your `SignalR` service and a `CORS policy` to the `ConfigureServices` method. |
| 38 | +Create a `Hubs` folder and add a `ChatHub.cs` file: |
23 | 39 |
|
24 | | - ```csharp |
25 | | - public void ConfigureServices(IServiceCollection services) |
| 40 | +```csharp |
| 41 | +// Hubs/ChatHub.cs |
| 42 | +using Microsoft.AspNetCore.SignalR; |
| 43 | + |
| 44 | +namespace ChatServer.Hubs; |
| 45 | + |
| 46 | +public class ChatHub : Hub |
| 47 | +{ |
| 48 | + public async Task SendMessage(string user, string message) |
26 | 49 | { |
27 | | - services.AddRazorPages(); |
28 | | - services.AddSignalR(); |
29 | | - |
30 | | - services.AddCors(o => o.AddPolicy( |
31 | | - "CorsPolicy", |
32 | | - builder => builder |
33 | | - .AllowAnyOrigin() |
34 | | - .AllowAnyMethod() |
35 | | - .AllowAnyHeader() |
36 | | - )); |
| 50 | + await Clients.All.SendAsync("ReceiveMessage", user, message); |
37 | 51 | } |
38 | | - ``` |
| 52 | +} |
| 53 | +``` |
| 54 | + |
| 55 | +A [Hub](https://learn.microsoft.com/aspnet/core/signalr/hubs) is a high-level pipeline that allows clients and the server to call methods on each other. The `SendMessage` method above broadcasts a message to every connected client. |
| 56 | + |
| 57 | +### Configure the server |
39 | 58 |
|
40 | | -4. In your `Configure` method, add your CORS policy and `Hubs` endpoint |
| 59 | +Replace the contents of `Program.cs` with: |
41 | 60 |
|
42 | | - ```csharp |
43 | | - app.UseCors("CorsPolicy"); |
| 61 | +```csharp |
| 62 | +// Program.cs |
| 63 | +using ChatServer.Hubs; |
44 | 64 |
|
45 | | - app.UseEndpoints(endpoints => |
| 65 | +var builder = WebApplication.CreateBuilder(args); |
| 66 | + |
| 67 | +builder.Services.AddSignalR(); |
| 68 | + |
| 69 | +// CORS is required when the Uno client runs on a different origin |
| 70 | +// (e.g. Uno WASM served from a different port). |
| 71 | +builder.Services.AddCors(options => |
| 72 | +{ |
| 73 | + options.AddPolicy("CorsPolicy", policy => |
46 | 74 | { |
47 | | - endpoints.MapRazorPages(); |
48 | | - endpoints.MapHub<Hubs.[YourProjectHub]>("/yourProjectHub"); |
| 75 | + policy |
| 76 | + .AllowAnyHeader() |
| 77 | + .AllowAnyMethod() |
| 78 | + // In production, replace with your app's specific origin(s). |
| 79 | + .SetIsOriginAllowed(_ => true) |
| 80 | + .AllowCredentials(); |
49 | 81 | }); |
50 | | - ``` |
| 82 | +}); |
| 83 | + |
| 84 | +var app = builder.Build(); |
| 85 | + |
| 86 | +app.UseCors("CorsPolicy"); |
| 87 | + |
| 88 | +app.MapHub<ChatHub>("/chatHub"); |
| 89 | + |
| 90 | +app.Run(); |
| 91 | +``` |
| 92 | + |
| 93 | +> [!IMPORTANT] |
| 94 | +> When your Uno WASM app is served from a different origin than the SignalR server, CORS must be configured on the server. The example above uses `SetIsOriginAllowed(_ => true)` for development convenience. In production, restrict this to your app's actual origin(s) and use `AllowCredentials()` since SignalR requires it for certain transports. |
| 95 | +
|
| 96 | +Start the server: |
| 97 | + |
| 98 | +```dotnetcli |
| 99 | +dotnet run --project ChatServer |
| 100 | +``` |
| 101 | + |
| 102 | +Note the URL displayed (for example, `https://localhost:5001`). You will use this in the client. |
| 103 | + |
| 104 | +## Step 2 — Add SignalR to the Uno client |
| 105 | + |
| 106 | +### Install the NuGet package |
| 107 | + |
| 108 | +In your Uno Platform project, install the SignalR .NET client package: |
| 109 | + |
| 110 | +```dotnetcli |
| 111 | +cd YourUnoApp |
| 112 | +dotnet add package Microsoft.AspNetCore.SignalR.Client |
| 113 | +``` |
| 114 | + |
| 115 | +### Connect to the hub |
| 116 | + |
| 117 | +The following example shows a minimal code-behind approach. You can adapt this to MVVM, Uno.Extensions, or any pattern your app uses. |
| 118 | + |
| 119 | +```csharp |
| 120 | +using Microsoft.AspNetCore.SignalR.Client; |
| 121 | +using Microsoft.UI.Xaml; |
| 122 | +using Microsoft.UI.Xaml.Controls; |
| 123 | + |
| 124 | +namespace YourUnoApp; |
| 125 | + |
| 126 | +public sealed partial class ChatPage : Page |
| 127 | +{ |
| 128 | + private HubConnection? _connection; |
| 129 | + |
| 130 | + public ChatPage() |
| 131 | + { |
| 132 | + this.InitializeComponent(); |
| 133 | + this.Loaded += ChatPage_Loaded; |
| 134 | + this.Unloaded += ChatPage_Unloaded; |
| 135 | + } |
| 136 | + |
| 137 | + private async void ChatPage_Loaded(object sender, RoutedEventArgs e) |
| 138 | + { |
| 139 | + _connection = new HubConnectionBuilder() |
| 140 | + .WithUrl("https://localhost:5001/chatHub") |
| 141 | + .WithAutomaticReconnect() |
| 142 | + .Build(); |
| 143 | + |
| 144 | + // Listen for messages from the server |
| 145 | + _connection.On<string, string>("ReceiveMessage", (user, message) => |
| 146 | + { |
| 147 | + // Marshal back to the UI thread |
| 148 | + DispatcherQueue.TryEnqueue(() => |
| 149 | + { |
| 150 | + MessagesListView.Items.Add($"{user}: {message}"); |
| 151 | + }); |
| 152 | + }); |
| 153 | + |
| 154 | + try |
| 155 | + { |
| 156 | + await _connection.StartAsync(); |
| 157 | + StatusText.Text = "Connected"; |
| 158 | + } |
| 159 | + catch (Exception ex) |
| 160 | + { |
| 161 | + StatusText.Text = $"Connection failed: {ex.Message}"; |
| 162 | + } |
| 163 | + } |
| 164 | + |
| 165 | + private async void ChatPage_Unloaded(object sender, RoutedEventArgs e) |
| 166 | + { |
| 167 | + if (_connection is not null) |
| 168 | + { |
| 169 | + await _connection.DisposeAsync(); |
| 170 | + } |
| 171 | + } |
| 172 | + |
| 173 | + private async void SendButton_Click(object sender, RoutedEventArgs e) |
| 174 | + { |
| 175 | + if (_connection is not null && |
| 176 | + !string.IsNullOrWhiteSpace(UserTextBox.Text) && |
| 177 | + !string.IsNullOrWhiteSpace(MessageTextBox.Text)) |
| 178 | + { |
| 179 | + await _connection.InvokeAsync( |
| 180 | + "SendMessage", |
| 181 | + UserTextBox.Text, |
| 182 | + MessageTextBox.Text); |
| 183 | + |
| 184 | + MessageTextBox.Text = string.Empty; |
| 185 | + } |
| 186 | + } |
| 187 | +} |
| 188 | +``` |
| 189 | + |
| 190 | +### Add the UI (XAML) |
| 191 | + |
| 192 | +```xml |
| 193 | +<Page x:Class="YourUnoApp.ChatPage" |
| 194 | + xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" |
| 195 | + xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> |
| 196 | + |
| 197 | + <StackPanel Padding="20" Spacing="8"> |
| 198 | + <TextBlock x:Name="StatusText" Text="Connecting..." /> |
| 199 | + |
| 200 | + <TextBox x:Name="UserTextBox" PlaceholderText="Your name" /> |
| 201 | + <TextBox x:Name="MessageTextBox" PlaceholderText="Message" /> |
| 202 | + <Button Content="Send" Click="SendButton_Click" /> |
| 203 | + |
| 204 | + <ListView x:Name="MessagesListView" Height="300" /> |
| 205 | + </StackPanel> |
| 206 | +</Page> |
| 207 | +``` |
| 208 | + |
| 209 | +## Step 3 — Run the app |
| 210 | + |
| 211 | +1. Start the **ChatServer** project. |
| 212 | +2. Run your **Uno app** on any target platform. |
| 213 | +3. Enter a name and message, then click **Send**. The message is broadcast to all connected clients in real time. |
| 214 | + |
| 215 | +## Handling reconnection |
| 216 | + |
| 217 | +The `WithAutomaticReconnect()` call in the example above configures the client to retry after 0, 2, 10, and 30 seconds when the connection is lost. You can customize retry delays: |
| 218 | + |
| 219 | +```csharp |
| 220 | +var connection = new HubConnectionBuilder() |
| 221 | + .WithUrl("https://localhost:5001/chatHub") |
| 222 | + .WithAutomaticReconnect(new[] |
| 223 | + { |
| 224 | + TimeSpan.Zero, |
| 225 | + TimeSpan.FromSeconds(2), |
| 226 | + TimeSpan.FromSeconds(10), |
| 227 | + TimeSpan.FromSeconds(30), |
| 228 | + TimeSpan.FromSeconds(60) |
| 229 | + }) |
| 230 | + .Build(); |
| 231 | +``` |
| 232 | + |
| 233 | +You can subscribe to connection state events: |
| 234 | + |
| 235 | +```csharp |
| 236 | +connection.Reconnecting += error => |
| 237 | +{ |
| 238 | + DispatcherQueue.TryEnqueue(() => StatusText.Text = "Reconnecting..."); |
| 239 | + return Task.CompletedTask; |
| 240 | +}; |
| 241 | + |
| 242 | +connection.Reconnected += connectionId => |
| 243 | +{ |
| 244 | + DispatcherQueue.TryEnqueue(() => StatusText.Text = "Reconnected"); |
| 245 | + return Task.CompletedTask; |
| 246 | +}; |
| 247 | + |
| 248 | +connection.Closed += error => |
| 249 | +{ |
| 250 | + DispatcherQueue.TryEnqueue(() => StatusText.Text = "Disconnected"); |
| 251 | + return Task.CompletedTask; |
| 252 | +}; |
| 253 | +``` |
| 254 | + |
| 255 | +For more details, see [Handle lost connection](https://learn.microsoft.com/aspnet/core/signalr/dotnet-client#handle-lost-connection). |
| 256 | + |
| 257 | +## Platform-specific considerations |
| 258 | + |
| 259 | +| Platform | Transport | Notes | |
| 260 | +|----------|-----------|-------| |
| 261 | +| WebAssembly | WebSockets | Requires CORS on the server. The `Microsoft.AspNetCore.SignalR.Client` NuGet package works in Uno WASM without additional configuration. | |
| 262 | +| Desktop (Skia) | WebSockets | Works out of the box on Windows, macOS, and Linux. | |
| 263 | +| iOS / Android | WebSockets | Works out of the box. Ensure the server URL is reachable from the device or emulator (avoid `localhost`; use the machine's IP or a tunnel such as [dev tunnels](https://learn.microsoft.com/azure/developer/dev-tunnels/overview)). | |
| 264 | +| Windows (WinUI) | WebSockets | Works out of the box. | |
| 265 | + |
| 266 | +## Sample app |
| 267 | + |
| 268 | +The [ChatSignalR sample](https://github.com/unoplatform/Uno.Samples/tree/master/UI/ChatSignalR) in the Uno.Samples repository demonstrates a full chat application using SignalR with an Uno Platform client and an ASP.NET Core server. |
| 269 | + |
| 270 | +## Further reading |
51 | 271 |
|
52 | | -You now have a SignalR service that you can use with your Uno application! |
| 272 | +- [Overview of ASP.NET Core SignalR](https://learn.microsoft.com/aspnet/core/signalr/introduction) |
| 273 | +- [ASP.NET Core SignalR .NET Client](https://learn.microsoft.com/aspnet/core/signalr/dotnet-client) |
| 274 | +- [Tutorial: Get started with ASP.NET Core SignalR](https://learn.microsoft.com/aspnet/core/tutorials/signalr) |
| 275 | +- [SignalR Hubs](https://learn.microsoft.com/aspnet/core/signalr/hubs) |
| 276 | +- [Azure SignalR Service](https://learn.microsoft.com/azure/azure-signalr/signalr-overview) |
0 commit comments