In this episode, we are going to build a REPLACE_HERE.
End results will look like this:
Let's get to it.
The following prerequisites are needed for this demo.
Download the latest version of the .NET 6.0 SDK here.
📘 The demo below also applies to
ASP.NET Coreversions 3.0, 3.1, and 5.0, but we are using 6.0 for this demo.
For this demo, we are going to use the latest version of Visual Studio 2022 Preview.
In order to build Blazor apps, the ASP.NET and web development workload needs to be installed, so if you do not have that installed let's do that now.
In the following demo we will create a REPLACE_HERE and I will show you REPLACE_HERE.
Now let's add some quick SignalR chat sample code.
You can follow these instructions here Use ASP.NET Core SignalR with Blazor, and skip to Authentication and Authorization in SignalR, or follow along. The code below is basically the same code as the Microsoft sample, except with some minor UI changes.
Add a NuGet reference to Microsoft.AspNetCore.SignalR.Client.
Create a Hubs folder and add a ChatHub.cs file, with the following content:
using Microsoft.AspNetCore.SignalR;
namespace BlazorServerSignalRApp.Server.Hubs
{
public class ChatHub : Hub
{
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
}Open the Program.cs file and replace the code with this:
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using SignalRSecurity.Data;
using Microsoft.AspNetCore.ResponseCompression;
using BlazorServerSignalRApp.Server.Hubs;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddSingleton<WeatherForecastService>();
builder.Services.AddResponseCompression(opts =>
{
opts.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
new[] { "application/octet-stream" });
});
var app = builder.Build();
app.UseResponseCompression();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.MapBlazorHub();
app.MapHub<ChatHub>("/chathub");
app.MapFallbackToPage("/_Host");
app.Run();Finally, replace the contents of the Pages/Index.razor file with this:
@page "/"
@using Microsoft.AspNetCore.SignalR.Client
@inject NavigationManager NavigationManager
@implements IAsyncDisposable
<PageTitle>Index</PageTitle>
<style>
ul.no-bullets {
list-style-type: none;
margin: 0;
padding: 0;
}
</style>
<div>
<label>
User
</label>
</div>
<div>
<input @bind="userInput" />
</div>
<div>
<label>
Message
</label>
</div>
<div>
<input @bind="messageInput" size="50" />
</div>
<br />
<button @onclick="Send" disabled="@(!IsConnected)">Send</button>
<hr>
<ul class="no-bullets" id="messagesList">
@foreach (var message in messages)
{
<li>@message</li>
}
</ul>
@code {
private HubConnection? hubConnection;
private List<string> messages = new List<string>();
private string? userInput;
private string? messageInput;
protected override async Task OnInitializedAsync()
{
hubConnection = new HubConnectionBuilder()
.WithUrl(NavigationManager.ToAbsoluteUri("/chathub"))
.Build();
hubConnection.On<string, string>("ReceiveMessage", (user, message) =>
{
var encodedMsg = $"{DateTime.UtcNow} {user}: {message}";
messages.Add(encodedMsg);
InvokeAsync(StateHasChanged);
});
await hubConnection.StartAsync();
}
private async Task Send()
{
if (hubConnection is not null)
{
await hubConnection.SendAsync("SendMessage", userInput, messageInput);
}
}
public bool IsConnected => hubConnection?.State == HubConnectionState.Connected;
public async ValueTask DisposeAsync()
{
if (hubConnection is not null)
{
await hubConnection.DisposeAsync();
}
}
}For more information about Blazor, check the links in the resources section below.
The complete code for this demo can be found in the link below.
| Resource Title | Url |
|---|---|
| The .NET Show with Carl Franklin | https://www.youtube.com/playlist?list=PL8h4jt35t1wgW_PqzZ9USrHvvnk8JMQy_ |
| Download .NET | https://dotnet.microsoft.com/en-us/download |
| Use ASP.NET Core SignalR with Blazor | https://docs.microsoft.com/en-us/aspnet/core/blazor/tutorials/signalr-blazor?view=aspnetcore-7.0&tabs=visual-studio&pivots=server |
| Overview of ASP.NET Core SignalR | https://docs.microsoft.com/en-us/aspnet/core/signalr/introduction?view=aspnetcore-7.0 |
| Authentication and authorization in ASP.NET Core SignalR | |
| https://docs.microsoft.com/en-us/aspnet/core/signalr/authn-and-authz?view=aspnetcore-7.0 | |
| Security considerations in ASP.NET Core SignalR | https://docs.microsoft.com/en-us/aspnet/core/signalr/security?view=aspnetcore-7.0 |