ASP.NET Core Web API and Blazor - MVC and related patterns
Web API really is an implementation of the MVC pattern (or rather a trimmed-down "MC" - without the V, because it returns data, not views), whereas Blazor is not MVC - it is a component-based UI model, closer to React/Angular than to traditional MVC.
A reminder: MVC (Model-View-Controller)
- Model - data and business logic
- View - the presentation layer (what the user sees)
- Controller - receives the request, coordinates the Model and View, returns a response
ASP.NET Core Web API as an implementation of MVC
Web API is in practice MVC without the V - instead of returning HTML (a View), it returns data (JSON/XML). The structure is very similar to WPF's MVVM - the Controller plays a bit of an intermediary role, much like the ViewModel.
Controller - the entry point of a request
[ApiController]
[Route("api/[controller]")]
public class OrdersController : ControllerBase
{
private readonly IOrderService _orderService; // DI
public OrdersController(IOrderService orderService)
{
_orderService = orderService;
}
[HttpGet("{id}")]
public async Task<ActionResult<OrderDto>> GetOrder(int id)
{
var order = await _orderService.GetOrderAsync(id);
if (order == null) return NotFound();
return Ok(order);
}
[HttpPost]
public async Task<ActionResult<OrderDto>> CreateOrder(CreateOrderRequest request)
{
var order = await _orderService.CreateOrderAsync(request);
return CreatedAtAction(nameof(GetOrder), new { id = order.Id }, order);
}
}
[ApiController] - an attribute that turns on API-specific conventions: automatic model validation (400 Bad Request without a manual if (!ModelState.IsValid)), automatic binding of parameters from the route/body, better error messages.
Model - a DTO instead of a domain entity
An important practice: don't return EF Core entities directly from the API - you return a DTO (Data Transfer Object).
// A domain entity - used internally, has navigations, may have technical fields
public class Order
{
public int Id { get; set; }
public Customer Customer { get; set; } // nawigacja EF - ryzyko cyklicznej serializacji
public ICollection<OrderItem> Items { get; set; }
}
// A DTO - exactly what the client should see, nothing more
public record OrderDto(int Id, string CustomerName, decimal Total, List<OrderItemDto> Items);
Why this matters:
- You avoid accidentally leaking sensitive data (e.g. a PasswordHash field in a User entity)
- You avoid circular references in JSON serialisation (Order.Customer.Orders.First().Customer...)
- The API contract is independent of the database structure - you can change the EF model without breaking the API
Routing - attribute-based (dominant in Web API)
[HttpGet("{id}")] // GET api/orders/5
[HttpGet("search")] // GET api/orders/search
[HttpGet("{id}/items")] // GET api/orders/5/items
[HttpPost] // POST api/orders
[HttpPut("{id}")] // PUT api/orders/5
[HttpDelete("{id}")] // DELETE api/orders/5
Middleware pipeline - IoC in practice
var app = builder.Build();
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
This is exactly the IoC mechanism with middleware - the framework itself decides when to call which middleware, and in what order; you only register "what should happen".
Minimal APIs - an alternative to controllers (a newer approach, .NET 6+)
app.MapGet("/api/orders/{id}", async (int id, IOrderService orderService) =>
{
var order = await orderService.GetOrderAsync(id);
return order != null ? Results.Ok(order) : Results.NotFound();
});
This is still MVC-like conceptually (an endpoint = a mini-controller), just without a Controller class - lighter, less boilerplate, popular in microservices.
The layered architecture of Web API
Controller (MVC)
↓
Service (logika biznesowa)
↓
Repository (EF Core)
↓
Baza danych
[ApiController]
public class OrdersController : ControllerBase
{
private readonly IOrderService _orderService; // the Controller does NOT know EF Core directly
// ...
}
The Controller shouldn't contain business logic or call DbContext directly - this is analogous to what we said about the ViewModel in WPF: a thin coordinating layer, with all the logic in the service.
Blazor - why it is NOT MVC
This is a key point to make in an interview, because wrongly assigning Blazor to MVC is a sign of superficial knowledge. Blazor is a component framework (philosophically similar to React or Angular), not MVC.
Two Blazor hosting models
Blazor Server - the logic runs on the server, and the UI is updated through SignalR (WebSocket) in real time.
Blazor WebAssembly (WASM) - all the C# code is compiled to WebAssembly and executed in the browser, without round trips to the server on every interaction.
A Blazor component - the equivalent of "View + some logic"
@page "/orders/{id:int}"
@inject IOrderService OrderService
<h3>Order #@Order?.Id</h3>
@if (Order == null)
{
<p>Loading...</p>
}
else
{
<p>Klient: @Order.CustomerName</p>
<p>Total: @Order.Total PLN</p>
<button @onclick="ShipOrder">Ship the order</button>
}
@code {
[Parameter] public int Id { get; set; }
private OrderDto Order;
protected override async Task OnInitializedAsync()
{
Order = await OrderService.GetOrderAsync(Id);
}
private async Task ShipOrder()
{
await OrderService.ShipOrderAsync(Id);
Order = await OrderService.GetOrderAsync(Id);
}
}
Why it is closer to MVVM than MVC
This is an interesting observation to show in an interview - a Blazor component combines what in MVC was split into a Controller + View into one unit:
| MVC | Blazor | MVVM (WPF) | |
|---|---|---|---|
| UI (markup) | View (.cshtml) |
The HTML section in .razor |
XAML |
| Presentation logic | Controller | The @code section in the same file |
ViewModel (a separate file) |
| UI refresh | A full page reload (or manual JS) | Automatic re-rendering when the state changes | Automatic through INotifyPropertyChanged/binding |
| DI | Through the controller's constructor | @inject |
Through the ViewModel's constructor |
@inject in Blazor is DI - exactly the same Microsoft.Extensions.DependencyInjection container you already know from Web API and WPF:
// Program.cs
builder.Services.AddScoped<IOrderService, OrderService>();
@inject IOrderService OrderService
This shows the consistency of the .NET ecosystem - the same DI mechanism works identically in Web API, Blazor and (as we showed) in WPF.
Component lifecycle - the equivalent of the lifecycle we discussed with WPF
protected override void OnInitialized() { } // odpowiednik konstruktora ViewModelu
protected override async Task OnInitializedAsync() { } // dla async inicjalizacji (np. pierwsze pobranie danych)
protected override void OnParametersSet() { } // when the [Parameter]s change
protected override bool ShouldRender() => true; // controls whether to re-render (an optimisation)
StateHasChanged - manually refreshing the UI
private async Task LoadDataInBackground()
{
var data = await _service.GetDataAsync();
Orders = data;
StateHasChanged(); // tell Blazor to re-render the component
}
This is conceptually very close to what PropertyChanged does in WPF - there the framework listens for the event and refreshes the UI itself, here you sometimes have to call it explicitly (e.g. when the state change happens outside Blazor's normal event cycle, such as in a callback from an external service).
Blazor Server vs WASM - practical differences (a common question)
| Blazor Server | Blazor WebAssembly | |
|---|---|---|
| Where the code runs | The server | The browser (WASM) |
| Communication | SignalR (a persistent WebSocket connection) | Directly in the browser, HTTP to the API when needed |
| Interaction latency | Depends on the network (every click = a round trip to the server) | Immediate (the code is local) |
| Download size | Small (no .NET runtime in the browser) | Large (downloads the whole .NET runtime) |
| Offline | ❌ Doesn't work without a connection | ✅ Can work offline (PWA) |
| Server scaling | Every user = persistent state on the server (memory, a SignalR connection) | The server only serves static files + the API |
Blazor United / Blazor Web App (.NET 8+) - worth mentioning that newer .NET lets you mix both models in one application, with so-called render modes (Static SSR, Server, WebAssembly, Auto) chosen per component.
Where Web API and Blazor meet in the architecture
A typical layout, analogous to what we discussed with WPF:
Blazor WASM (frontend, runs in the browser)
↓ HttpClient → HTTP calls
ASP.NET Core Web API (backend)
↓
Service (logika biznesowa)
↓
EF Core → baza danych
// W komponencie Blazor WASM
@inject HttpClient Http
@code {
private List<OrderDto> orders;
protected override async Task OnInitializedAsync()
{
orders = await Http.GetFromJsonAsync<List<OrderDto>>("api/orders");
}
}
This is structurally identical to the WPF → API architecture we discussed with async/EF Core - only the frontend technology differs (Blazor WASM in the browser instead of WPF on the desktop), but the backend layers (Controller → Service → Repository → EF) are exactly the same.
Blazor Server, on the other hand, doesn't need a separate Web API in the middle - a component can inject IOrderService directly through DI and call it locally (because the code runs on the server anyway) - this is an architectural difference they sometimes ask about: "Do you need a separate Web API in Blazor Server?" - the answer: not necessarily, you can inject services directly, unless the same backend also has to serve other clients (mobile, WPF, Blazor WASM) - then a Web API as a shared layer makes sense.
Summary of the conceptual difference
"ASP.NET Core Web API really is an implementation of MVC, just without the View - the Controller returns data (JSON) instead of HTML. Blazor, on the other hand, is a component framework, conceptually closer to MVVM or React than to classic MVC - a component combines in one file what in MVC would be split into View and Controller, and the component's state automatically synchronises with the UI, much like binding in WPF. Both use the same DI mechanism from Microsoft.Extensions.DependencyInjection, which shows the consistency of the whole ASP.NET Core ecosystem."