loading experience

Guide

Guide to ASP.NET Core: APIs, real time and secure sign-in

Guide to ASP.NET Core: APIs, real time and secure sign-in

Minimal APIs and validation, documentation with OpenAPI 3.1, rate limiting, passkeys with Identity, gRPC and SignalR, Razor Pages and Blazor in .NET 10: the ASP.NET Core articles gathered in a single guide.

In this guide

  1. Minimal APIs in .NET 10: automatic data validation
  2. OpenAPI 3.1 in ASP.NET Core 10: documenting your APIs
  3. Rate limiting in ASP.NET Core: protecting APIs and forms
  4. Passkeys in ASP.NET Core Identity: signing in without passwords
  5. gRPC in .NET: fast communication between services
  6. SignalR: real-time applications with ASP.NET Core
  7. Razor Pages: when they are the right choice
  8. Blazor in .NET 10: persistent state with [PersistentState]

Minimal APIs in .NET 10: automatic data validation

Minimal APIs are the most direct way to write HTTP APIs in ASP.NET Core. Up to .NET 9, validating incoming data had to be done by hand or with external libraries; in .NET 10 it is built in.

Invalid data never reaches the endpoint code.
Invalid data never reaches the endpoint code.

Enabling validation

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddValidation();

var app = builder.Build();

app.MapPost("/customers", (NewCustomer customer) =>
    TypedResults.Created($"/customers/{customer.Email}", customer));

app.Run();

public record NewCustomer(
    [Required, StringLength(100)] string Name,
    [Required, EmailAddress] string Email,
    [Range(18, 120)] int Age);

If the request body does not respect the rules, the endpoint is not even executed: the framework responds with 400 Bad Request and a ProblemDetails object listing the invalid fields.

What gets validated

  • Route, query and header parameters with validation attributes.
  • JSON bodies, including nested objects and collections.
  • Types implementing IValidatableObject for rules involving several fields.

Excluding an endpoint

app.MapPost("/raw-import", (RawData data) => Results.Accepted())
   .DisableValidation();

Good practices

Attribute validation checks the shape of the data; business rules (does the customer already exist? is the product available?) stay in the application service. Keeping the two levels separate makes both easier to test.


OpenAPI 3.1 in ASP.NET Core 10: documenting your APIs

An OpenAPI document describes your APIs in a way people and tools can read: automatically generated clients, tests, gateways, developer portals. ASP.NET Core generates it straight from the code.

The document is generated from code and always stays in sync.
The document is generated from code and always stays in sync.

Minimal configuration

builder.Services.AddOpenApi();

var app = builder.Build();
app.MapOpenApi();          // /openapi/v1.json

In .NET 10 the document follows the OpenAPI 3.1 specification, aligned with JSON Schema: nullable types and schemas are described more precisely.

Descriptions from XML comments

By enabling XML documentation generation in the project, the <summary> comments on methods and types become descriptions in the OpenAPI document.

<PropertyGroup>
  <GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup>
/// <summary>Returns a product given its code.</summary>
/// <param name="code">Item code, for example ABC-123.</param>
static async Task<Results<Ok<Product>, NotFound>> FindProduct(string code, ICatalog catalog) =>
    await catalog.FindAsync(code) is { } p ? TypedResults.Ok(p) : TypedResults.NotFound();

app.MapGet("/products/{code}", FindProduct);

In YAML too

app.MapOpenApi("/openapi/{documentName}.yaml");

Exposing it safely

The document reveals the structure of your APIs: in production consider publishing it only to authenticated users or only in the development environment. For a browsable interface, add dedicated tools such as Scalar or Swagger UI.


Rate limiting in ASP.NET Core: protecting APIs and forms

A login form without limits invites brute-force attempts; a public API without limits can be saturated by a single client. ASP.NET Core includes a rate limiting middleware configurable per endpoint.

Each client has its own counter: whoever overdoes it gets 429, the others do not.
Each client has its own counter: whoever overdoes it gets 429, the others do not.

Configuration

builder.Services.AddRateLimiter(o =>
{
    o.RejectionStatusCode = StatusCodes.Status429TooManyRequests;

    o.AddPolicy("login", ctx => RateLimitPartition.GetFixedWindowLimiter(
        ctx.Connection.RemoteIpAddress?.ToString() ?? "unknown",
        _ => new FixedWindowRateLimiterOptions
        {
            PermitLimit = 5,
            Window = TimeSpan.FromMinutes(1)
        }));

    o.AddTokenBucketLimiter("api", t =>
    {
        t.TokenLimit = 100;
        t.TokensPerPeriod = 20;
        t.ReplenishmentPeriod = TimeSpan.FromSeconds(10);
    });
});

var app = builder.Build();
app.UseRateLimiter();

Applying the policies

app.MapPost("/login", Login).RequireRateLimiting("login");
app.MapGroup("/api").RequireRateLimiting("api");

With Razor Pages and MVC you use the [EnableRateLimiting("login")] attribute on the page or controller.

Available algorithms

  • Fixed window: N requests per interval; simple and predictable.
  • Sliding window: avoids spikes straddling two windows.
  • Token bucket: allows short bursts while keeping a sustainable average.
  • Concurrency: limits simultaneous requests, useful for heavy operations.

Behind a proxy

If the application sits behind IIS, a load balancer or a CDN, the client IP address arrives in forwarded headers: configure UseForwardedHeaders before the rate limiter, otherwise every user will look like the same client.


Passkeys in ASP.NET Core Identity: signing in without passwords

Passwords get reused, stolen and guessed. Passkeys, based on the WebAuthn and FIDO2 standards, replace the password with a pair of cryptographic keys: the private key stays on the user's device, protected by fingerprint, face or PIN.

The private key never leaves the user's device.
The private key never leaves the user's device.

Why they are more secure

  • Phishing resistant: a passkey only works on the site it was created for; a fake site cannot use it.
  • No secrets on the server: the server stores only the public key; a database breach reveals no usable credentials.
  • More convenient: nothing to remember, sign in with a gesture.

What changes in ASP.NET Core 10

ASP.NET Core Identity integrates passkey support: registering a passkey for the user, signing in with a passkey and managing the passkeys linked to the account. The Blazor Web App template with individual accounts already includes the necessary pages, a good starting point for other project types too.

A realistic adoption path

  1. Offer passkeys as an additional option to existing users.
  2. Suggest it at the right moment, for example right after a successful sign-in.
  3. Keep a secure recovery method, because users change phones.
  4. When most users have one, consider making the password optional.

In the meantime

builder.Services.Configure<IdentityOptions>(o =>
{
    o.Lockout.MaxFailedAccessAttempts = 5;
    o.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(15);
    o.SignIn.RequireConfirmedEmail = true;
});

As long as passwords exist, lockout after failed attempts, confirmed email and two-factor authentication remain essential.


gRPC in .NET: fast communication between services

gRPC is a remote procedure call framework based on HTTP/2 and Protocol Buffers. Messages are binary, compact and fast to serialise, and the contract between client and server is defined in a shared file.

Often both are used: REST outside, gRPC between services.
Often both are used: REST outside, gRPC between services.

The contract

syntax = "proto3";
option csharp_namespace = "Warehouse";

service Stock {
  rpc Availability (AvailabilityRequest) returns (AvailabilityReply);
  rpc Movements (MovementsRequest) returns (stream Movement);
}

message AvailabilityRequest { string code = 1; }
message AvailabilityReply { string code = 1; int32 quantity = 2; }
message MovementsRequest { string code = 1; }
message Movement { string date = 1; int32 delta = 2; }

C# classes for client and server are generated automatically from the .proto file.

The server

public class StockService(IWarehouse warehouse) : Stock.StockBase
{
    public override async Task<AvailabilityReply> Availability(
        AvailabilityRequest req, ServerCallContext ctx)
    {
        var q = await warehouse.QuantityAsync(req.Code, ctx.CancellationToken);
        return new AvailabilityReply { Code = req.Code, Quantity = q };
    }
}

builder.Services.AddGrpc();
app.MapGrpcService<StockService>();

When to choose it

  • Communication between internal services, where performance and strict contracts matter.
  • Streaming data in one or both directions.
  • Clients in different languages: the same .proto file generates code for many languages.

When to stay with REST

For public APIs consumed by browsers and third parties, REST with JSON remains easier to explore and integrate. Browsers do not speak native gRPC: you need gRPC-Web or a gateway. Many architectures use both: REST towards the outside, gRPC between internal services.


SignalR: real-time applications with ASP.NET Core

SignalR lets the server send messages to clients the moment something happens, without the browser constantly polling for updates. It picks the best transport on its own: WebSockets when available, otherwise compatible alternatives.

The server notifies clients the moment something changes.
The server notifies clients the moment something changes.

A hub

public class NotificationsHub : Hub
{
    public async Task JoinGroup(string department)
    {
        await Groups.AddToGroupAsync(Context.ConnectionId, department);
    }
}

builder.Services.AddSignalR();
app.MapHub<NotificationsHub>("/hubs/notifications");

Sending from the server, from anywhere

With IHubContext an application service can notify clients even outside the hub, for example when an order changes status:

public class OrderService(IHubContext<NotificationsHub> hub)
{
    public async Task ShippedAsync(Order o)
    {
        // ...update the database...
        await hub.Clients.Group("logistics").SendAsync("orderShipped", o.Id);
    }
}
const conn = new signalR.HubConnectionBuilder()
    .withUrl("/hubs/notifications")
    .withAutomaticReconnect()
    .build();

conn.on("orderShipped", id => showAlert(`Order ${id} shipped`));
await conn.start();
await conn.invoke("JoinGroup", "logistics");

Good practices

  • Authenticate connections and check permissions in every hub method: a client can call any public method.
  • Send small events (identifiers, statuses) and let the client load details with a normal call.
  • With several server instances you need a backplane, such as Redis or Azure SignalR Service, so that messages reach everyone.
  • Plan for reconnection: after an interruption the client must recover what it missed.

Razor Pages: when they are the right choice

In ASP.NET Core you can build web interfaces with MVC, Razor Pages or Blazor. Razor Pages is often underrated, yet it is the easiest model to maintain for many real projects.

The redirect after saving avoids duplicate form submissions.
The redirect after saving avoids duplicate form submissions.

One page, one model

Each page has a .cshtml file for the markup and a PageModel class with the request handlers. Everything about a screen lives in one place.

public class ContactModel(IEmailService email) : PageModel
{
    [BindProperty]
    public ContactRequest Input { get; set; } = new();

    public void OnGet() { }

    public async Task<IActionResult> OnPostAsync()
    {
        if (!ModelState.IsValid) return Page();
        await email.SendAsync(Input);
        TempData["Message"] = "Thank you, we will reply soon.";
        return RedirectToPage();
    }
}

Why it works well

  • File-based routing: the folder structure is the URL structure.
  • Secure by default: antiforgery protection is active on forms with no configuration.
  • Natural Post-Redirect-Get pattern, which avoids double form submissions.
  • Server-side HTML: great for SEO, accessibility and slow devices.

Multiple handlers on the same page

public async Task<IActionResult> OnPostDeleteAsync(int id) { /* ... */ return RedirectToPage(); }
public async Task<IActionResult> OnPostPublishAsync(int id) { /* ... */ return RedirectToPage(); }
<form method="post" asp-page-handler="Delete" asp-route-id="@item.Id">
    <button type="submit">Delete</button>
</form>

When to prefer something else

If you need highly interactive interfaces with continuous updates without reloading the page, Blazor is a better fit. If you only build APIs for a mobile app or a separate frontend, Minimal APIs are leaner. But for corporate websites, members' areas and business applications, Razor Pages is hard to beat for simplicity.


Blazor in .NET 10: persistent state with [PersistentState]

With prerendering, a Blazor component runs first on the server to produce the initial HTML, then again when it becomes interactive. Without care, data is loaded twice and the page "flickers".

With [PersistentState] the data loaded during prerendering is reused.
With [PersistentState] the data loaded during prerendering is reused.

The solution in .NET 10

The [PersistentState] attribute saves a property's value during prerendering and restores it when the component becomes interactive.

@page "/products"
@inject ICatalog Catalog

@if (Products is null)
{
    <p>Loading...</p>
}
else
{
    <ul>
        @foreach (var p in Products)
        {
            <li>@p.Name - @p.Price.ToString("C")</li>
        }
    </ul>
}

@code {
    [PersistentState]
    public List<Product>? Products { get; set; }

    protected override async Task OnInitializedAsync()
    {
        // in the interactive phase the value has already been restored
        Products ??= await Catalog.ListAsync();
    }
}

In earlier versions you had to use PersistentComponentState by hand, registering callbacks and keys: now the attribute is enough.

Other Blazor improvements

  • More robust reconnection handling in Blazor Server circuits.
  • Framework scripts delivered as fingerprinted static assets, so browsers can cache them for a long time.
  • Not-found page handling better integrated with routing.

When to choose Blazor

Blazor is ideal for business applications and rich interfaces written entirely in C#, sharing models and logic between server and client. For public sites with lots of content and little interactivity, Razor Pages or static rendering remain lighter.


Comments (0)

No comments yet.

Leave a comment