Reader small image

You're reading from  Web API Development with ASP.NET Core 8

Product typeBook
Published inApr 2024
PublisherPackt
ISBN-139781804610954
Edition1st Edition
Concepts
Right arrow
Author (1)
Xiaodi Yan
Xiaodi Yan
author image
Xiaodi Yan

Xiaodi Yan is a seasoned software engineer with a proven track record in the IT industry. Since 2015, he has been awarded Microsoft MVP, showcasing his dedication to and expertise in .NET, AI, DevOps, and cloud computing. He is also a Microsoft Certified Trainer (MCT), Azure Solutions Architect Expert, and LinkedIn Learning instructor. Xiaodi often presents at conferences and user groups, leveraging his extensive experience to engage and inspire audiences. Based in Wellington, New Zealand, he spearheads the Wellington .NET User Group, fostering a vibrant community of like-minded professionals. Connect with Xiaodi on LinkedIn to stay updated on his latest insights.
Read more about Xiaodi Yan

Right arrow

Getting Started with SignalR

In Chapter 1, we introduced the concept of real-time web APIs. Various technologies can be used to implement real-time web APIs, such as gRPC streaming, long polling, Server-Sent Events (SSE), WebSockets, and so on. Microsoft provides an open-source library called SignalR to simplify the implementation of real-time web APIs. In this chapter, we will introduce the basics of SignalR and how to use SignalR to implement real-time web APIs.

We will cover the following topics in this chapter:

  • Recap of real-time web APIs
  • Setting up SignalR
  • Building SignalR clients
  • Using authentication and authorization in SignalR
  • Managing users and groups
  • Sending messages from other services
  • Configuring SignalR hubs and clients

By the end of this chapter, you will be able to use SignalR to implement real-time web APIs.

Technical requirements

To follow the steps in this chapter, you can download the source code from the GitHub repository at https://github.com/PacktPublishing/Web-API-Development-with-ASP.NET-Core-8/tree/main/samples/chapter13. You can use VS 2022 or VS Code to open the solutions.

You also need to install the following software:

  • Node.js: Node.js is a JavaScript runtime built on Chrome’s V8 JavaScript engine. You can download the latest version of Node.js from https://nodejs.org/en/. We will use it to install the required packages for the TypeScript client.

Recap of real-time web APIs

We introduced a few technologies that can be used to implement real-time web APIs in Chapter 1. Each technology has its pros and cons. To simplify the implementation of real-time web APIs, Microsoft provides SignalR, which supports multiple transports, such as WebSockets, SSE, and long polling. SignalR will automatically choose the best transport based on the client’s capabilities. On top of that, SignalR provides a simple programming model to implement real-time web APIs. Developers do not need to worry about the underlying transport details; instead, they can focus on the business logic.

SignalR was first introduced for ASP.NET in 2013. As of now, SignalR has been rewritten for ASP.NET Core and is included in the ASP.NET Core framework. So, there are two different versions of SignalR: one for ASP.NET and one for ASP.NET Core. If you are using ASP.NET Core, you do not need to install any additional packages to use SignalR. There are also some...

Setting up SignalR

In this section, we will build a simple chat application using SignalR. The chat application will allow users to send messages to a public chat room. The messages will be broadcast to all connected clients. This application contains four projects:

  • ChatApp.Server: This is the ASP.NET Core web API project that provides a SignalR hub
  • ChatApp.TypeScriptClient: This is a client application written in TypeScript
  • ChatApp.BlazorClient: This is a client application written in Blazor, which is a web framework for building client-side applications using C#

Important note

The code of this sample is based on the official SignalR sample provided by Microsoft. You can find the original source code at https://github.com/aspnet/SignalR-samples/tree/main/ChatSample. We added the Blazor and MAUI clients to the sample.

The ChatApp.Server application is a simple ASP.NET Core web API application that is used to provide a SignalR hub. A SignalR hub is a class...

Building SignalR clients

This section will demonstrate how to use SignalR in different platforms by building three SignalR clients that consume the same SignalR hub provided by the ChatApp.Server application. The code for SignalR is largely the same across platforms, making it easy to learn and implement in your own applications. As such, you can refer to any of these applications to gain an understanding of how to consume a SignalR service in your client applications.

Building a TypeScript client

The first client we will build is a TypeScript client. This application is just a normal HTML page that uses the SignalR JavaScript client library to communicate with the SignalR hub. TypeScript is a superset of JavaScript that provides static typing and other features to help developers write better JavaScript code. TypeScript code is compiled into JavaScript code, so it can run in any JavaScript runtime, such as browsers and Node.js. To learn more about TypeScript, you can visit the...

Using authentication and authorization in SignalR

In the previous section, we used the Hub class to implement a simple chat app. The Clients.All.SendAsync method is used to send a message to all connected clients. Sometimes, we may want to send a message to a specific client or a group of clients. To manage users and groups, we need to know the identity of the user. In this section, we will explore how to use authentication and authorization in SignalR.

By default, SignalR uses a ClaimTypes.NameIdentifier claim to differentiate users. The ClaimTypes.NameIdentifier claim is used to uniquely identify a user. We introduced claim-based authorization in Chapter 8, so we will follow the steps from that chapter to add authentication and authorization to the SignalR server application. If you are not familiar with ASP.NET Core authentication and authorization, you can refer to Chapter 8 for more details.

You can find the complete code of the sample in the chapter13/v2 folder of the GitHub...

Managing users and groups

In the previous section, we implemented basic authentication and authorization for the SignalR server. We also updated clients to authenticate users. In this section, we will explore how to manage users and groups in SignalR. We want to add features to the chat app to enable the following:

  • Allow users to know who is connected to the chat app
  • Allow users to send a message to a specific user
  • Allow users to join groups
  • Allow users to send a message to a specific group

You can find the complete code of the sample in the chapter13/v3 folder of the GitHub repository. Let’s start with the first feature.

Managing events in SignalR

SignalR provides events to notify clients when a user connects or disconnects. We can override the OnConnectedAsync() and OnDisconnectedAsync() methods to handle these events. The following code shows how to override the OnConnectedAsync() method:

public override async Task OnConnectedAsync(){
...

Sending messages from other services

So far, we have implemented a chat app that allows users to send messages to other users or groups. Sometimes, we need to send messages from other places. For example, when an event occurs, we may need to send a message to notify the users. In this section, we will explore how to send messages from other services. You can find the complete code of the sample in the chapter13/v4 folder of the GitHub repository.

We will add a REST API endpoint to allow other systems to send messages to the SignalR hub. Follow these steps to add a REST API endpoint in the ChatApp.Server application:

  1. Create the following models in the Models folder:
    public class SendToAllMessageModel{    public string FromUser { get; set; } = string.Empty;    public string Message { get; set; } = string.Empty;}public class SendToUserMessageModel{    public string FromUser { get; set; } = string.Empty;  ...

Configuring SignalR hubs and clients

SignalR provides a HubOptions class to configure SignalR hubs. Also, SignalR clients have some configuration options. In this section, we will explore how to configure SignalR hubs and clients. You can find the complete code of the sample in the chapter13/v5 folder of the GitHub repository.

Configuring SignalR hubs

Here are some of the configuration options for SignalR hubs:

  • KeepAliveInterval: This property determines the interval at which a keep-alive message is sent to clients. If a client does not receive a message from the server within this period of time, it will send a ping message to the server in order to maintain the connection. When changing this value, it is important to also adjust the serverTimeoutInMilliseconds or ServerTimeout option in the client. For best results, it is recommended to set the serverTimeoutInMilliseconds or ServerTimeout option to a value that is double the value of the KeepAliveInterval property....

Summary

SignalR is a powerful library that simplifies the process of building real-time web applications. In this chapter, we explored how to use SignalR to build a chat app. We introduced basic concepts of SignalR, such as hubs, clients, and connections. We created clients using TypeScript and Blazor, which demonstrated how to use both TypeScript and .NET to build SignalR clients. We also discussed how to send messages to a specific user or group and how to secure SignalR connections using JWT authentication. Additionally, we explored how to configure SignalR hubs and clients, such as configuring the keep-alive interval, configuring HTTP options, and configuring the automatic reconnect feature.

Although we have covered a lot of features, there is still more to explore, such as streaming. For more information, please refer to the official documentation: https://learn.microsoft.com/en-us/aspnet/core/signalr/introduction. In the next chapter, we will explore how to deploy ASP.NET...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Web API Development with ASP.NET Core 8
Published in: Apr 2024Publisher: PacktISBN-13: 9781804610954
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Xiaodi Yan

Xiaodi Yan is a seasoned software engineer with a proven track record in the IT industry. Since 2015, he has been awarded Microsoft MVP, showcasing his dedication to and expertise in .NET, AI, DevOps, and cloud computing. He is also a Microsoft Certified Trainer (MCT), Azure Solutions Architect Expert, and LinkedIn Learning instructor. Xiaodi often presents at conferences and user groups, leveraging his extensive experience to engage and inspire audiences. Based in Wellington, New Zealand, he spearheads the Wellington .NET User Group, fostering a vibrant community of like-minded professionals. Connect with Xiaodi on LinkedIn to stay updated on his latest insights.
Read more about Xiaodi Yan