Blazor Server Documentation
Blazor Server is a web framework for building interactive client-side web UIs with .NET. Blazor Server apps run on the server with an ASP.NET Core app, and UI updates are handled over SignalR. This model provides a smooth user experience with minimal latency.
How Blazor Server Works
When a Blazor Server app is loaded in the browser:
- A WebSocket connection is established between the browser and the server using SignalR.
- The browser downloads a small JavaScript file and a .NET runtime.
- The .NET runtime runs on the server, and the app's UI events are sent to the server over the WebSocket connection.
- The Blazor Server framework handles component rendering on the server.
- Any UI changes are sent back to the browser as a diff of the DOM.
- The JavaScript in the browser applies these changes to the DOM.
Key Benefits of Blazor Server
- Full .NET Experience: Leverage the full power of the .NET ecosystem on the server.
- Code Sharing: Easily share code between the client and server.
- Reduced Client Load: Most processing happens on the server, leading to lighter client-side applications.
- Enhanced Security: Sensitive code and logic remain on the server.
Getting Started with Blazor Server
To create a new Blazor Server project, you can use the .NET CLI:
dotnet new blazorserver -o MyBlazorServerApp
This command creates a new directory named MyBlazorServerApp
containing the project files. You can then navigate into the project directory and run the application:
cd MyBlazorServerApp
dotnet run
Building Your First Blazor Server Component
Blazor components are typically written in C# and Razor syntax. Here's a simple example of a counter component:
@page "/counter"
Counter
Current count: @currentCount
@code {
private int currentCount = 0;
private void IncrementCount()
{
currentCount++;
}
}
In this component:
@page "/counter"
defines the route for this component.@currentCount
displays the current value of thecurrentCount
variable.@onclick="IncrementCount"
is an event handler that calls theIncrementCount
method when the button is clicked.- The
@code
block contains the C# logic for the component.
Key Concepts and APIs
.razor
files: Components written in Razor syntax (HTML + C#).@inject
directive: For dependency injection of services.@bind
attribute: For two-way data binding.- SignalR: The underlying technology for real-time communication.
Microsoft.AspNetCore.SignalR.Client
: Namespace for SignalR clients.
Important Consideration
Blazor Server requires a stable and low-latency connection to the server for a good user experience. It is not ideal for users with poor or intermittent internet connectivity.
Deployment
Blazor Server apps are deployed as standard ASP.NET Core applications. You can deploy them to IIS, Azure App Service, Docker containers, and other platforms that support ASP.NET Core.