Telerik blogs
DotNetT2 Light_1200x303

Today’s apps are expected to provide up-to-date information without the need to hit an update button. How can we make this possible? An interesting way is with the use of SignalR.

Something very common in software development are applications that make requests to a server and wait for the server to process this request and return the data.

But what if we need this data at the exact moment we make a request, like in a game for example, where we can’t have delays?

To meet this need, ASP.NET Core has a technology called SignalR. In this article, we will get an introduction to SignalR and create a simple example that will provide real-time data to an application. For that we will use the minimal APIs available in .NET 6.

What Is SignalR?

SignalR is a library for ASP.NET developers that simplifies the process of adding real-time web functionality to applications.

With SignalR we can make server content available to connected clients instantly as it becomes available instead of the server waiting for a client to request new data.

SignalR is an excellent choice for handling “real-time” web functionality through ASP.NET. A common example of its use is in the development of chats where the user needs to have their message sent immediately the same way they receive it. While chat is common, it’s not the only example of using SignalR. Monitoring apps, collaborative forms and real-time games are also great use cases.

For detailed information about SignalR, you can access the official Microsoft website through this link: Introduction to SignalR.

Hands-on Approach

In this article, we will create a practical example of using SignalR in a simple way with a minimal API available in .NET 6.

Note: In these examples, we will use Visual Studio 2022, as well as the .NET 6 SDK.

If you don’t know the concept of minimal APIs, I suggest taking a look at this article: Low Ceremony, High Value: A Tour of Minimal APIs in .NET 6. It provides a great approach to the subject.

You can access the full code of the example used in this article through this link: source code.

Creating the Server

First, let’s create a server. So, run the commands below in the terminal:

dotnet new web -o MainSignalServer
cd MainSignalServer
dotnet add package Microsoft.AspNetCore.SignalR

With these commands, we create our server (MainSignalServer) and add the “Microsoft.AspNetCore.SignalR” package that we need to implement SignalR on the server.

Creating the Hub

A Hub allows the client and server to call methods to each other directly. SignalR uses a Hub instead of controllers like in ASP.NET MVC. For that, we need to create a class that will inherit from the Hub class.

So within the project, create a class called “MainHub” and replace your code with this:

using Microsoft.AspNetCore.SignalR;

public class MainHub : Hub
{
    public async IAsyncEnumerable<DateTime> Streaming(CancellationToken cancellationToken)
    {
        while (true)
        {
            yield return DateTime.UtcNow;
            await Task.Delay(1000, cancellationToken);
        }
    }
}

For this example, we are returning an “IAsyncEnumerable” which is a type added in more recent versions of C#. We are also passing a “CancellationToken” parameter which allows us to cancel the action at any time. We also added the “yield” so that the client doesn’t need a class to store the state.

Now, we need to add the SignalR configuration and create a route to our server. For that, replace the Program class code with this:

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSignalR();

var app = builder.Build();
app.MapHub<MainHub>("/current-time");

app.Run();

Our server is ready—now just give the command below in the terminal, and it will be running.

dotnet watch run

Creating the Client

Now let’s create a simple app to consume the information our server is providing in real time.

Then, in another terminal, execute the following commands:

dotnet new console -o MainSignalClient
cd MainSignalClient
dotnet add package Microsoft.AspNetCore.SignalR.Client

Now, inside the created project, create a class called “MainClient” and replace the code with the code below:

using Microsoft.AspNetCore.SignalR.Client;

public class MainClient
{
    public static async Task ExecuteAsync()
    {
        //Replace port "7054" with the port running the MainSignalServer project
        var uri = "https://localhost:7054/current-time";

        await using var connection = new HubConnectionBuilder().WithUrl(uri).Build();

        await connection.StartAsync();

        await foreach (var date in connection.StreamAsync<DateTime>("Streaming"))
        {
            Console.WriteLine(date);
        }
    }
}

In the class we created, we are defining a method to consume the data that the server is making available in real time For that, we create a connection to the Hub, passing our server’s URL, which returns a list of dates and displays it on the terminal.

Now we just need to call this method in our app’s Program. So, replace the code of the Program class with the code below:

await MainClient.ExecuteAsync();

Now, just start the client project with this command in the console, and check the result:

dotnet watch run

The client console is displaying the current date and time made available by our server.

Client Console Result lists dates and times

Conclusion

In this article, we created simple examples of using SignalR and minimal APIs available in .NET 6.

We created a server that makes real-time information available to a console app.

The purpose of this example was just to demonstrate the use of SignalR, but you can do amazing things with this feature of ASP.NET Core. There are many examples available on the internet like chats, games and more!


assis-zang-bio
About the Author

Assis Zang

Assis Zang is a software developer from Brazil, developing in the .NET platform since 2017. In his free time, he enjoys playing video games and reading good books. You can follow him at: LinkedIn and Github.

Related Posts

Comments

Comments are disabled in preview mode.