Introduction
Web development is undergoing a rapid transformation, with frameworks continually evolving to meet modern application demands. Among these, Blazor, a framework from Microsoft, stands out as a groundbreaking technology. It empowers developers to build dynamic web applications using C# and .NET—without relying on JavaScript.
What is Blazor?
Blazor is a web framework that enables developers to build interactive user interfaces using C#, HTML, and the .NET ecosystem. Unlike traditional JavaScript-based frameworks, Blazor uses WebAssembly (Wasm) to run .NET code directly in the browser.
Hosting Models:
Blazor Server: Runs application logic on the server and uses SignalR for real-time communication.
Blazor WebAssembly: Runs application logic on the client browser using WebAssembly.
Each model has its strengths, catering to different use cases. Let’s dive deeper into their workings.
Blazor Server
How It Works
In Blazor Server, the UI events and logic are executed on the server. SignalR, a real-time messaging library, maintains a persistent connection between the client and the server to synchronize UI changes. This ensures a lightweight client and centralized application state management.
Advantages:
Fast initial load times.
Secure, as sensitive logic stays on the server.
Works on devices with limited processing power.
Example: Fetching Server Time
@page "/servertime"
@inject IJSRuntime JSRuntime
<h3>Server Time</h3>
<p>Time: @serverTime</p>
<button @onclick="UpdateServerTime">Get Latest Time</button>
@code {
private string serverTime;
protected override async Task OnInitializedAsync()
{
await UpdateServerTime();
}
private async Task UpdateServerTime()
{
var response = await HttpClient.GetStringAsync("https://worldtimeapi.org/api/timezone/etc/utc");
serverTime = $"Server Time: {response}";
}
}
Key Concepts:
SignalR handles communication.
Razor Components dynamically render UI.
Lightweight UI footprint, but requires a reliable server connection.
Blazor WebAssembly
How It Works
In Blazor WebAssembly (Wasm), the entire application—including .NET runtime—is downloaded to the browser. This enables client-side execution of logic and reduces dependency on the server during runtime.
Advantages:
Offline capabilities.
High performance for compute-intensive tasks.
No server dependency for UI updates.
Example: Client Clock
@page "/clientclock"
<h3>Client Clock</h3>
<p>Current Time: @currentTime</p>
@code {
private string currentTime;
protected override void OnInitialized()
{
Timer timer = new Timer(1000);
timer.Elapsed += (sender, args) => {
currentTime = DateTime.Now.ToString("hh:mm:ss tt");
InvokeAsync(StateHasChanged);
};
timer.Start();
}
}
Key Concepts:
WebAssembly runs .NET code directly in the browser.
Full independence from the server.
Rich interactive experiences with better offline support.
Advanced Use Cases
Integrating External APIs
Blazor simplifies API integration using dependency injection and strongly-typed models.
// Register HttpClient in Program.cs
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri("https://api.example.com") });
// Fetch data in Razor Component
@page "/datafetch"
<h3>Weather Data</h3>
<ul>
@foreach (var weather in weatherForecasts)
{
<li>@weather.Date: @weather.TemperatureC°C (@weather.Summary)</li>
}
</ul>
@code {
private WeatherForecast[] weatherForecasts;
protected override async Task OnInitializedAsync()
{
weatherForecasts = await HttpClient.GetFromJsonAsync<WeatherForecast[]>("weatherforecast");
}
public class WeatherForecast
{
public DateTime Date { get; set; }
public int TemperatureC { get; set; }
public string Summary { get; set; }
}
}
Authentication with OpenID Connect (OIDC)
Blazor supports robust authentication mechanisms such as Okta and Azure AD.
// Configure authentication in Program.cs
builder.Services.AddOidcAuthentication(options =>
{
builder.Configuration.Bind("OIDC", options.ProviderOptions);
});
// appsettings.json
{
"OIDC": {
"Authority": "https://your-okta-domain",
"ClientId": "your-client-id"
}
}
Conclusion
Blazor is revolutionizing the way developers build web applications by leveraging the power of C# and .NET. Whether you need real-time interactivity with Blazor Server or offline capabilities with Blazor WebAssembly, the framework has something for everyone.
With its seamless integration with .NET tools and libraries, Blazor simplifies complex application development, allowing developers to focus on delivering exceptional user experiences.
Blazor isn't just another web framework—it's a paradigm shift for .NET developers. The next wave of interactive, scalable, and performant applications is just a Blazor project away.
Start building with Blazor today and unlock a world of possibilities!
Top comments (0)