Complete examples for connecting to the SpecificationQuestionnaireHub
Install
@microsoft/signalr
Configure
Hub URL + Auth token
Register Handlers
connection.on(...)
Subscribe
invoke("SubscribeToSpecification")
| Endpoint | /default/hubs/specification-questionnaires |
|---|---|
| Authentication | JWT Bearer token (via accessTokenFactory) |
| Client Methods | SubscribeToSpecification, UnsubscribeFromSpecificationId |
| Server Events | SpecificationQuestionnaireSectionUpdated |
| Transports | WebSocket, Server-Sent Events, Long Polling |
import * as signalR from "@microsoft/signalr";
export class SpecificationQuestionnaireClient {
private connection: signalR.HubConnection;
private subscribedSpecifications: Set<string> = new Set();
constructor(private hubUrl: string, private getToken: () => Promise<string>) {
this.connection = new signalR.HubConnectionBuilder()
.withUrl(hubUrl, {
accessTokenFactory: getToken
})
.withAutomaticReconnect([0, 2000, 5000, 10000, 30000])
.configureLogging(signalR.LogLevel.Information)
.build();
this.setupEventHandlers();
this.setupReconnection();
}
private setupEventHandlers(): void {
this.connection.on("SpecificationQuestionnaireSectionUpdated", (data) => {
console.log("Questionnaire section updated:", data);
this.onQuestionnaireUpdated?.(data);
});
}
private setupReconnection(): void {
this.connection.onreconnected(async () => {
console.log("Reconnected - resubscribing to specifications");
for (const specId of this.subscribedSpecifications) {
await this.connection.invoke("SubscribeToSpecification", specId);
}
});
}
async connect(): Promise<void> {
await this.connection.start();
}
async subscribe(specificationId: string): Promise<void> {
await this.connection.invoke("SubscribeToSpecification", specificationId);
this.subscribedSpecifications.add(specificationId);
}
async unsubscribe(specificationId: string): Promise<void> {
await this.connection.invoke("UnsubscribeFromSpecificationId", specificationId);
this.subscribedSpecifications.delete(specificationId);
}
async disconnect(): Promise<void> {
this.subscribedSpecifications.clear();
await this.connection.stop();
}
// Event callback
onQuestionnaireUpdated?: (data: { specificationId: string; chapterType: string }) => void;
}
import { useEffect, useRef, useCallback, useState } from "react";
import * as signalR from "@microsoft/signalr";
export function useSpecificationQuestionnaires(specificationId, getToken) {
const connectionRef = useRef(null);
const [updates, setUpdates] = useState([]);
const [connectionState, setConnectionState] = useState("Disconnected");
useEffect(() => {
if (!specificationId) return;
const connection = new signalR.HubConnectionBuilder()
.withUrl("/default/hubs/specification-questionnaires", {
accessTokenFactory: getToken
})
.withAutomaticReconnect()
.build();
connection.on("SpecificationQuestionnaireSectionUpdated", (data) => {
setUpdates(prev => [data, ...prev]);
});
connection.onreconnected(async () => {
setConnectionState("Connected");
await connection.invoke("SubscribeToSpecification", specificationId);
});
connection.onclose(() => setConnectionState("Disconnected"));
const start = async () => {
try {
await connection.start();
setConnectionState("Connected");
await connection.invoke("SubscribeToSpecification", specificationId);
} catch (err) {
console.error("SignalR connection failed:", err);
setConnectionState("Error");
}
};
start();
connectionRef.current = connection;
return () => {
connection.stop();
};
}, [specificationId, getToken]);
const clearUpdates = useCallback(() => setUpdates([]), []);
return { updates, connectionState, clearUpdates };
}
using Microsoft.AspNetCore.SignalR.Client;
public class SpecificationQuestionnaireSignalRClient : IAsyncDisposable
{
private readonly HubConnection _connection;
private readonly HashSet<Guid> _subscriptions = new();
public event Action<Guid, string>? OnQuestionnaireSectionUpdated;
public SpecificationQuestionnaireSignalRClient(string hubUrl, Func<Task<string>> tokenProvider)
{
_connection = new HubConnectionBuilder()
.WithUrl(hubUrl, options =>
{
options.AccessTokenProvider = tokenProvider;
})
.WithAutomaticReconnect()
.Build();
_connection.On<QuestionnaireSectionDto>("SpecificationQuestionnaireSectionUpdated", dto =>
{
OnQuestionnaireSectionUpdated?.Invoke(dto.SpecificationId, dto.ChapterType);
});
_connection.Reconnected += async _ =>
{
foreach (var specId in _subscriptions)
await _connection.InvokeAsync("SubscribeToSpecification", specId);
};
}
public async Task ConnectAsync() => await _connection.StartAsync();
public async Task SubscribeAsync(Guid specificationId)
{
await _connection.InvokeAsync("SubscribeToSpecification", specificationId);
_subscriptions.Add(specificationId);
}
public async Task UnsubscribeAsync(Guid specificationId)
{
await _connection.InvokeAsync("UnsubscribeFromSpecificationId", specificationId);
_subscriptions.Remove(specificationId);
}
public async ValueTask DisposeAsync()
{
_subscriptions.Clear();
await _connection.DisposeAsync();
}
private record QuestionnaireSectionDto(Guid SpecificationId, string ChapterType);
}
withAutomaticReconnect() — Handles transient disconnections without manual intervention.
onreconnected handler.
accessTokenFactory returns a valid, non-expired JWT token. The token must have the required scopes for the Specification API.withAutomaticReconnect() to handle this automatically. If using Long Polling, ensure keep-alive is configured on the server.onreconnected handler to re-invoke SubscribeToSpecification.