15. City Manager API (III)

City Manager API with SignalR

Introduction to SignalR

SignalR is a library for ASP.NET developers that simplifies the process of adding real-time web functionality to applications. Real-time web functionality is the ability to have server code push content to connected clients instantly as it becomes available, rather than having the server wait for a client to request new data.

Key Points:

Working Principle of SignalR

SignalR provides a simple API for creating server-to-client remote procedure calls (RPC) that call JavaScript functions in client browsers from server-side .NET code. SignalR also includes API for connection management (for instance, connect and disconnect events), grouping connections, and authorization.

Implementing SignalR in City Manager API

Let's assume we have a scenario in our City Manager API where we want to notify all connected clients whenever a change is made to the city data (such as adding a new city or updating existing city data). We can achieve this using SignalR.

Here's an example of how to implement this:

Setting Up SignalR Hub

First, we need to set up our SignalR hub, which is a server-side component. In the hub, we can define methods that will be called from the client side.

public class CityHub : Hub
{
    public async Task NotifyCityChanges(string message)
    {
        await Clients.All.SendAsync("ReceiveCityNotification", message);
    }
}

In this hub, we have a method NotifyCityChanges that will be called whenever there are changes in city data. This method sends the message to all connected clients.

Configuring Startup

Next, we need to configure SignalR in the Startup.cs file.

public void ConfigureServices(IServiceCollection services)
{
    services.AddSignalR();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapHub<CityHub>("/cityHub");
    });
}

Here, we first add SignalR services in ConfigureServices method, and then map our CityHub to a route in Configure method.

Calling Hub Methods from Controller

Now, in our city controller, we will call the NotifyCityChanges method of the hub whenever a change is made.

[HttpPost]
public async Task<IActionResult> CreateCity([FromBody] City city)
{
    // Code for creating city...

    await _hubContext.Clients.All.SendAsync("ReceiveCityNotification", "A new city has been added.");

    return Ok(city);
}

In this example, we send a notification to all clients when a new city is added.

Connecting from Client

Finally, the client needs to connect to this hub and define a method to receive the notifications.

var connection = new signalR.HubConnectionBuilder().withUrl("/cityHub").build();

connection.on("ReceiveCityNotification", function (message) {
    console.log(message);
});

connection.start().catch(function (err) {
    return console.error(err.toString());
});

In this JavaScript code, we first build a connection to the hub, then define a method to handle the notifications. Finally, we start the connection.

Conclusion

With SignalR, we can easily add real-time functionality to our application. In this City Manager API example, we used it to send notifications to all clients whenever city data is changed. This makes our application more interactive and improves the user experience.

Reference

The content in this document is based on the original notes provided in Azerbaijani. For further details, you can refer to the original document using the following link:

Original Note - Azerbaijani Version