Skip to content

Azure SignalR Service content rewrite #2775

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
Mar 26, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 30 additions & 24 deletions docs/real-time/snippets/signalr/SignalR.ApiService/Program.cs
Original file line number Diff line number Diff line change
@@ -1,12 +1,21 @@
var builder = WebApplication.CreateBuilder(args);
using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.AspNetCore.Http.Connections;

var builder = WebApplication.CreateBuilder(args);

builder.AddServiceDefaults();

builder.Services.AddProblemDetails();

var isServerlessMode = builder.Configuration.GetValue<bool>("IS_SERVERLESS");

if (isServerlessMode)
if (!isServerlessMode)
{
builder.Services.AddSignalR()
.AddNamedAzureSignalR("signalr");
}
else
{
builder.Services.AddSingleton(sp =>
{
Expand All @@ -19,41 +28,38 @@
.BuildServiceManager();
});
}
else
{
builder.Services.AddSignalR()
.AddNamedAzureSignalR("signalr");
}

var app = builder.Build();

app.UseExceptionHandler();

var options = new JsonSerializerOptions(JsonSerializerDefaults.Web)
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
};

if (isServerlessMode)
{
app.MapPost("/negotiate", async (ServiceManager serviceManager, string? userId) =>
app.MapPost("/chathub/negotiate", async (ServiceManager sm, ILogger<Program> logger) =>
{
var healthy = await serviceManager.IsServiceHealthy(CancellationToken.None);
if (healthy is false)
{
return Results.Problem("SignalR service is not healthy.");
}
var hubContext = await sm.CreateHubContextAsync("chathub", CancellationToken.None);

NegotiationResponse negotiateResponse = await hubContext.NegotiateAsync();

var hubContext = await serviceManager.CreateHubContextAsync(HubEndpoints.ChatHubWithoutRouteSlash, CancellationToken.None);
var negotiateResponse = await hubContext.NegotiateAsync(new NegotiationOptions
return Results.Json(negotiateResponse, new JsonSerializerOptions(JsonSerializerDefaults.Web)
{
UserId = userId ?? "user1"
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
});

return Results.Ok(negotiateResponse);
});

var serviceManager = app.Services.GetRequiredService<ServiceManager>();
var context = await serviceManager.CreateHubContextAsync(HubEndpoints.ChatHubWithoutRouteSlash, CancellationToken.None);
// try in the command line `CURL -X POST https://localhost:53282/broadcast` to broadcast messages to the clients
app.MapPost("/broadcast", async (ServiceManager sm) =>
{
var hubContext = await sm.CreateHubContextAsync("chathub", CancellationToken.None);

await context.Clients.All.SendAsync(
HubEventNames.MessageReceived,
new UserMessage("server", "Started..."));
await hubContext.Clients.All.SendAsync(
HubEventNames.MessageReceived,
new UserMessage("server", "Started..."));
});
}
else
{
Expand Down
14 changes: 1 addition & 13 deletions docs/real-time/snippets/signalr/SignalR.AppHost/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,25 +9,13 @@
: AzureSignalRServiceMode.Default)
.RunAsEmulator();

void IsServerlessEnvironmentVariable(EnvironmentCallbackContext context)
{
context.EnvironmentVariables["IS_SERVERLESS"] = isServerless;
}

var apiService = builder.AddProject<Projects.SignalR_ApiService>("apiservice")
.WithReference(signalR)
.WaitFor(signalR)
.WithEnvironment(IsServerlessEnvironmentVariable);
.WithEnvironment("IS_SERVERLESS", isServerless.ToString());

var web = builder.AddProject<Projects.SignalR_Web>("webfrontend")
.WithReference(apiService)
.WaitFor(apiService);

if (isServerless)
{
web.WithReference(signalR)
.WaitFor(signalR)
.WithEnvironment(IsServerlessEnvironmentVariable);
}

builder.Build().Run();
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />

<PackageReference Include="Microsoft.Extensions.Http.Resilience" Version="9.2.0" />
<PackageReference Include="Microsoft.Extensions.Http.Resilience" Version="9.3.0" />
<PackageReference Include="Microsoft.Extensions.ServiceDiscovery" Version="9.1.0" />
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.11.2" />
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.11.2" />
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@

namespace SignalR.Web.Components.Pages;
namespace SignalR.Web.Components.Pages;

public sealed partial class Home : IAsyncDisposable
{
Expand Down Expand Up @@ -47,18 +46,15 @@ protected override async Task OnAfterRenderAsync(bool firstRender)

protected override async Task OnInitializedAsync()
{
var api = Configuration.GetValue<bool>("IS_SERVERLESS")
? Configuration.GetUriFromConnectionString("signalr")
: Configuration.GetServiceHttpsUri("apiservice");
var apiUri = Configuration.GetServiceHttpsUri("apiservice");

var builder = new UriBuilder(api)
var builder = new UriBuilder(apiUri)
{
Path = HubEndpoints.ChatHub
};

_hubConnection = new HubConnectionBuilder()
.WithUrl(builder.Uri)
.WithStatefulReconnect()
.WithAutomaticReconnect()
.Build();

Expand Down Expand Up @@ -135,7 +131,7 @@ private Task SetIsTypingAsync(bool isTyping)
return Task.CompletedTask;
}

return _hubConnection?.InvokeAsync(
return _hubConnection?.SendAsync(
HubClientMethodNames.ToggleUserTyping,
new UserAction(Name: _username, IsTyping: _isTyping = isTyping)) ?? Task.CompletedTask;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

<ItemGroup>
<PackageReference Include="Blazor.LocalStorage" Version="9.0.1" />
<PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="9.0.2" />
<PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="9.0.3" />
</ItemGroup>

<ItemGroup>
Expand Down
Loading