LESSON 3 OF 14

3. Shared Message Models and Type-Safe Communication

Design shared DTOs for notifications, chat, and task events; validate Hub parameters, handle return values and errors, and align TypeScript models with the JavaScript client.

45 dk 57

Introduction

In the first two lessons, we examined SignalR architecture, the Hub concept, and basic communication with a JavaScript client. Establishing a connection is only the beginning of a production application. The client and server also need a clear, consistent, and verifiable contract for the data they exchange. If notifications, chat messages, and task progress are represented as unrelated strings and parameter lists, maintenance becomes increasingly difficult as the application grows.

In this lesson, we will create shared message models and DTOs. We will represent notification, chat, and task events consistently, validate Hub parameters, use predictable return values and controlled error responses, and align C# models with TypeScript definitions. The goal is not only cleaner code, but also a communication contract that can be tested and evolved deliberately.

1. Designing the message contract

A SignalR message contract is the data agreement between the client and server. It should define field names, data types, required fields, allowed values, and error behavior. Let us begin by defining event types and a common result structure.

public enum RealtimeEventType
{
    Notification,
    ChatMessage,
    TaskProgress
}

public sealed record RealtimeEvent(
    string EventId,
    RealtimeEventType Type,
    string Title,
    string? Body,
    DateTimeOffset OccurredAt,
    string? CorrelationId);

public sealed record ChatMessageDto(
    string MessageId,
    string SenderId,
    string SenderName,
    string Text,
    DateTimeOffset SentAt);

public sealed record TaskProgressDto(
    string TaskId,
    string TaskName,
    int Percent,
    string Status,
    DateTimeOffset UpdatedAt);

public sealed record CommandResult(
    bool Succeeded,
    string? ErrorCode = null,
    string? ErrorMessage = null);

A DTO is a model designed specifically for data moving into or out of an application boundary. Using a DTO as a Hub parameter is safer than exposing a database entity directly. It prevents internal fields from leaking to the client, keeps the real-time contract independent from the persistence model, and makes validation rules easier to understand.

For example, ChatMessageDto contains only fields that the client needs to display. A password hash, administrative note, or internal database value should never be added to this model. Using DateTimeOffset for OccurredAt, SentAt, and UpdatedAt also helps preserve time-zone information.

2. Making JSON serialization consistent

SignalR uses the JSON Hub protocol by default. C# properties are serialized as JSON fields and sent to the client. It is good practice to explicitly define a camelCase naming policy so clients use names such as eventId, occurredAt, and senderName. Sending enum values as strings instead of numbers also makes the client contract easier to read.

using System.Text.Json;
using System.Text.Json.Serialization;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddSignalR()
    .AddJsonProtocol(options =>
    {
        options.PayloadSerializerOptions.PropertyNamingPolicy =
            JsonNamingPolicy.CamelCase;
        options.PayloadSerializerOptions.Converters.Add(
            new JsonStringEnumConverter());
    });

var app = builder.Build();
app.MapHub<RealtimeHub>("/hubs/realtime");
app.Run();

With this configuration, RealtimeEventType.ChatMessage is normally sent to the client as "ChatMessage". On the client, use the actual JSON contract and write chatMessage rather than assuming that the C# PascalCase property names are transmitted unchanged.

Define serialization rules centrally. If one Hub emits camelCase while another uses a different naming policy, clients will encounter confusing and inconsistent payloads.

3. A strongly typed Hub client

Calling client methods with SendAsync requires method names to be written as strings. A spelling mistake may therefore remain hidden until runtime. Instead, define the methods that the server can call in an interface.

public interface IRealtimeClient
{
    Task ReceiveNotification(RealtimeEvent message);
    Task ReceiveChatMessage(ChatMessageDto message);
    Task ReceiveTaskProgress(TaskProgressDto progress);
    Task ReceiveError(string code, string message);
}

public sealed class RealtimeHub : Hub<IRealtimeClient>
{
    public async Task<CommandResult> SendChatMessage(
        string recipientGroup,
        string text)
    {
        if (string.IsNullOrWhiteSpace(recipientGroup))
        {
            return new CommandResult(
                false, "group_required", "A group is required.");
        }

        if (string.IsNullOrWhiteSpace(text))
        {
            return new CommandResult(
                false, "message_required", "The message cannot be empty.");
        }

        if (text.Length > 500)
        {
            return new CommandResult(
                false, "message_too_long", "The message cannot exceed 500 characters.");
        }

        var message = new ChatMessageDto(
            Guid.NewGuid().ToString("N"),
            Context.UserIdentifier ?? "anonymous",
            Context.User?.Identity?.Name ?? "Unknown user",
            text.Trim(),
            DateTimeOffset.UtcNow);

        await Clients.Group(recipientGroup)
            .ReceiveChatMessage(message);

        return new CommandResult(true);
    }
}

When the Hub inherits from Hub<IRealtimeClient>, the compiler can check calls such as ReceiveChatMessage on the server. This does not automatically validate the JavaScript method name; the JavaScript client still registers the name as a string with connection.on. However, it reduces server-side naming mistakes and makes the Hub contract explicit.

4. Parameter validation and error responses

A Hub method can encounter two broad categories of errors. The first category consists of business validation failures that the user can correct: an empty message, an unavailable group, or text exceeding the allowed length. Returning a structured CommandResult lets the user interface display a clear message without parsing an exception string.

The second category consists of unexpected system failures, such as a database outage or a programming error. Internal exception details should not be exposed to the client. For controlled business conditions, HubException can be used when a message must be sent to the caller, but that message must be safe for public display.

public async Task<CommandResult> MarkTaskCompleted(string taskId)
{
    if (string.IsNullOrWhiteSpace(taskId))
    {
        return new CommandResult(
            false, "task_required", "A task identifier is required.");
    }

    var taskExists = await TaskExistsAsync(taskId);
    if (!taskExists)
    {
        return new CommandResult(
            false, "task_not_found", "The task was not found.");
    }

    try
    {
        await CompleteTaskAsync(taskId);
        return new CommandResult(true);
    }
    catch (Exception)
    {
        // Detailed information should be written to server logs.
        return new CommandResult(
            false, "operation_failed", "The operation could not be completed.");
    }
}

If a complex JSON payload does not match the expected shape, model binding or serialization can fail before the Hub method runs. For example, sending "seventy" for an integer percent property may cause the invocation to be rejected. Client-side TypeScript definitions are useful, but they do not replace runtime validation of user input.

5. Aligning TypeScript definitions with the client

The SignalR JavaScript client is written in TypeScript and can be installed from npm through @microsoft/signalr. Create application-specific TypeScript definitions for the messages used by your Hub.

export type RealtimeEventType =
  | "Notification"
  | "ChatMessage"
  | "TaskProgress";

export interface RealtimeEvent {
  eventId: string;
  type: RealtimeEventType;
  title: string;
  body?: string;
  occurredAt: string;
  correlationId?: string;
}

export interface ChatMessageDto {
  messageId: string;
  senderId: string;
  senderName: string;
  text: string;
  sentAt: string;
}

export interface CommandResult {
  succeeded: boolean;
  errorCode?: string;
  errorMessage?: string;
}

A DateTimeOffset value is usually received as an ISO 8601 string in the browser. Do not treat it as a JavaScript Date automatically; convert it explicitly with new Date(message.sentAt) when needed. The values in the TypeScript union must match the string enum values configured by the server.

import { HubConnectionBuilder, LogLevel } from "@microsoft/signalr";
import type { ChatMessageDto, CommandResult, TaskProgressDto } from "./models";

const connection = new HubConnectionBuilder()
  .withUrl("/hubs/realtime")
  .configureLogging(LogLevel.Information)
  .withAutomaticReconnect()
  .build();

connection.on("ReceiveChatMessage", (message: ChatMessageDto) => {
  console.log(`${message.senderName}: ${message.text}`);
});

connection.on("ReceiveTaskProgress", (progress: TaskProgressDto) => {
  console.log(`${progress.taskName}: ${progress.percent}%`);
});

async function sendMessage(group: string, text: string) {
  const result = await connection.invoke<CommandResult>(
    "SendChatMessage", group, text);

  if (!result.succeeded) {
    throw new Error(result.errorMessage ?? "The message could not be sent.");
  }
}

Register connection.on handlers before starting the connection. Also ensure that the order and types of arguments passed to invoke match the Hub method signature. In this example, SendChatMessage accepts two strings and returns a CommandResult.

6. Testing invalid requests

Testing only the successful path is not enough for a message contract. Try the following cases:

  • Send an empty or whitespace-only message.
  • Send a message longer than 500 characters.
  • Invoke the method with an empty group name.
  • Send a percent value below 0 or above 100.
  • Use an invalid date string instead of the expected ISO format.
  • Read sender on the client instead of the contract field senderName.

When an error occurs, inspect the browser Network and Console panels first, then review server logs. The error code returned to the client is intended for user-interface decisions. Detailed exception information and diagnostic data belong in server-side logs.

Practice exercise

  1. Create NotificationDto, ChatMessageDto, and TaskProgressDto models.
  2. Configure enum values to be serialized as strings.
  3. Define three methods in IRealtimeClient for notifications, chat messages, and task progress.
  4. Write a Hub method that returns CommandResult for empty messages and messages exceeding 500 characters.
  5. Create the TypeScript equivalents and register handlers with connection.on.
  6. Test successful, empty, and oversized message scenarios.

Conclusion

Shared DTOs make a SignalR communication contract explicit. Well-designed models reduce accidental data exposure, clarify client-server expectations, and make new features easier to add. Parameter validation prevents invalid data from moving deeper into the system, while structured return values distinguish user-correctable failures from unexpected system errors.

In the next lessons, we will use these contracts in more realistic scenarios involving user and group messaging, notifications, and task progress. The central principle remains the same: every message sent through SignalR should have a clear model, a verifiable contract, and a corresponding representation on the client.

Sources