Building Real-Time Web Apps with SignalR, WebAssembly, and ASP.NET Core API by info.odysseyx@gmail.com October 16, 2024 written by info.odysseyx@gmail.com October 16, 2024 0 comment 3 views 3 Have you ever worked on a chat application that needs to display messages in real time or reflect changes based on backend updates? One common method used previously is to poll the backend for changes at specific intervals. However, this approach is not ideal as it slows down the client-side application and increases traffic on the backend. One solution to this problem is Signal R. In this blog, we’ll look at how to build real-time web applications using three cutting-edge technologies. Signal R, WebAssemblyand ASP.NET Core API. SignalR simplifies the process of adding real-time web functionality, WebAssembly provides near-native performance for web apps, and ASP.NET Core API provides a powerful and scalable backend. Combining these technologies allows you to create responsive and performant web applications. Signal R A library for ASP.NET that enables real-time web functionality. This allows server-side code to push content to connected clients as soon as it becomes available. SignalR supports multiple communication protocols, including WebSockets, and automatically falls back to other compatible protocols for older browsers. This makes it an excellent choice for applications that require frequent updates, such as chat applications, games, or live data feeds. Create a new ASP.NET Core project First, create a new ASP.NET Core Web API project. Open a terminal or command prompt and run the following command: dotnet new webapi -n RealTimeApp This command creates a new ASP.NET Core Web API project as follows: RealTimeApp. Signal R installation Next, navigate to your project directory and install the SignalR package. cd RealTimeApp dotnet add package Microsoft.AspNetCore.SignalR SignalR Configuration program.cs opening program.cs Create a file and configure SignalR. your program.cs The file should look like this: var builder = WebApplication.CreateBuilder(args); builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); builder.Services.AddCors(options => { options.AddPolicy("CorsPolicy", builder => { builder.WithOrigins("http://localhost:5051") .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); }); }); builder.Services.AddControllers(); // Adding SignalR builder.Services.AddSignalR(); var app = builder.Build(); if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); app.UseCors("CorsPolicy"); app.UseRouting(); // Adding the endpoint for the ChatHub app.UseEndpoints(endpoints => { endpoints.MapControllers(); endpoints.MapHub("/chatHub"); }); app.Run(); Create a SignalR hub Create a new class called ChatHub.cs in project SendMessage method: using Microsoft.AspNetCore.SignalR; public class ChatHub : Hub { public async Task SendMessage(string user, string message) { await Clients.All.SendAsync("ReceiveMessage", user, message); } } Create a new Blazor WebAssembly project First, create a new Blazor WebAssembly project. Open a terminal or command prompt and run the following command: dotnet new blazorwasm -n RealTimeApp.Client This command creates a new Blazor WebAssembly project as follows: RealTimeApp.Client. Add SignalR client library Go to your project directory and add the SignalR client library. cd RealTimeApp.Client dotnet add package Microsoft.AspNetCore.SignalR.Client Create Blazor components Create a new Razor component for the chat interface. Just give it a name. Chat.razor. Add the following: Chat.razor: "/chat" @using Microsoft.AspNetCore.SignalR.Client @inject NavigationManager NavigationManager Chat { if (e.Key == "Enter") Send().GetAwaiter().GetResult(); })" class="form-control" /> Send @foreach (var message in messages) { @message } @code { private HubConnection hubConnection; private string userInput; private string messageInput; private List messages = new List(); protected override async Task OnInitializedAsync() { hubConnection = new HubConnectionBuilder() .WithUrl("http://localhost:5258/chathub") .Build(); hubConnection.On("ReceiveMessage", (user, message) => { var encodedMsg = $"{user}: {message}"; messages.Add(encodedMsg); InvokeAsync(StateHasChanged); }); await hubConnection.StartAsync(); } private async Task Send() { await hubConnection.SendAsync("SendMessage", userInput, messageInput); messageInput = string.Empty; } } Add navigation Chat.razor your Chat.razor You can access components through navigation. Please update NavMenu.razor The file that will contain the link to the chat component: Run the ASP.NET Core API: dotnet run --project RealTimeApp Run Blazor WebAssembly app: dotnet run --project RealTimeApp.Client Go to next /chat Check out the chat interface in the Blazor WebAssembly app. Using SignalR, you should be able to send messages that are broadcast in real time to all connected clients. In this blog we looked at how to build a real-time web application using: Signal R, WebAssemblyand ASP.NET Core API. We leveraged these technologies to create a responsive chat application that allows instantaneous updates without constant polling. SignalR facilitated real-time communication, WebAssembly provided near-native performance, and the ASP.NET Core API served as a powerful backend. We started by setting up the ASP.NET Core API and integrating SignalR to process real-time messages. We then created a Blazor WebAssembly client that interacted with the SignalR hub to send and receive messages. The combination of these technologies not only improves performance but also simplifies real-time web application development. I hope this tutorial has given you a solid foundation for building your own real-time application. To see the full source code and explore it in more detail, visit the GitHub repository. GitHub repository: RealTimeApp Feel free to clone the repository, experiment with the code, and extend the application to suit your needs. To learn more about this topic, check out these resources: Happy coding! Source link Share 0 FacebookTwitterPinterestEmail info.odysseyx@gmail.com previous post Explore Exciting Graphic Design Job Opportunities in Mumbai at DigiMedia – Apply Today! next post Evaluating generative AI: Best practices for developers You may also like How to strengthen AI security with MLSecOps December 6, 2024 The Sonos Arc Ultra raises the bar for home theater audio December 5, 2024 Aptera Motors will showcase its solar EV at CES 2025 December 3, 2024 How Chromebook tools strengthen school cybersecurity December 2, 2024 Nvidia unveils the ‘Swiss Army Knife’ of AI audio tools: Fugato November 26, 2024 Nvidia Blackwell and the future of data center cooling November 25, 2024 Leave a Comment Cancel Reply Save my name, email, and website in this browser for the next time I comment.