WESLEY WITSKEN

Postman with SignalR

Tue Dec 10 2024

Testing SignalR with Postman - useful tips.

Written by: Wesley Witsken

A radio tower.

Postman with SignalR - How to Test

The Problem

Over the last couple months, my coding journey has led me to learning Clean Architecture (thanks to Milan Jovanović), which has been challenging but rewarding. After learning how to create general .NET backend applications, Clean Architecture is the next step into learning how to create modular, testable, extendable applications (and improve my programming strategies).

Along the way I’ve grown increasingly tempted by the idea of creating a real-time board game application. This kind of project is perfect for SignalR, which is a Microsoft library which essentially abstracts away websocket communication on the server and client side (with graceful fallback options for other real-time protocols).

However, it’s a lot harder to test web socket connections than API endpoints. SignalR has a client library for C# and Javascript, but I don’t want to have to create an entire frontend app to test my backend while I’m making it.

Instead, I want to use Postman, which now includes support for Web Sockets. I struggled with it at first, but finally figured it out. This guide will hopefully help you, dear reader, avoid the same dumb pitfalls I ran into throughout the process.

Set Up Local SignalR Hub and Server

  1. Use HTTPS. You will want to use it anyway when you deploy this server - might as well get it working now.

  2. In your program.cs file, call the following:

    builder.Services.AddSignalR();
    
    ... {{other Program.cs components}} ...
    
    app.MapHub<YourHub>("/your-hub-endpoint");
    
  3. In YourHub.cs, make debugging easier by overriding the OnConnectedAsync method. Make sure to make it async. Add a nice little breakpoint.

Set Up Postman

  1. Get your localhost port. If using Kestrel (not a docker container) look at the console that pops up when you run your application.

  2. Using the HTTPS port number, create a Postman request to:

    wss://localhost:{{your_port}}/{{your-hub-endpoint}}
    
  3. IMPORTANT: Add this to your request body:

    {"protocol":"json","version":1}
    

    It is part of the communication required for SignalR to set up a connection. Be sure to include to last character - Postman shows this character as an ASCII unknown but it is actually ASCII character 0x1E.

  4. Hit the following buttons in Postman. This is where I got very hung up - you have to send the request, and then you can send the body.

Postman SignalR Request

And that’s it! Hope this helps - don’t make my silly mistakes.