Middleware
- Introduction
- Complete Example: Route Middleware
- Built-in Middleware
- Authenticate (
auth) - Redirect If Authenticated (
guest) - Ensure Email Is Verified (
verified) - Validate Signature (
signed) - Validate CSRF Token (
csrf) - Trim Strings (
trim-strings) - Throttling Requests (
throttle) - Cache Headers (
cache.headers) - Confirm Password (
password.confirm) - Token Abilities (
abilities,ability) - Laravel Middleware Without an Alias
- Authenticate (
- Defining Middleware
- Registering Middleware
- The Request Pipeline
- Not Yet Available
Complete Example: Route Middleware
Add this complete file to the Blog template:
// app/Providers/MiddlewareDemoProvider.cs
using DotBlaze;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace Blog.Providers;
public class DocumentationHeader : IRouteMiddleware
{
public async Task Handle(HttpContext context, Func<Task> next)
{
context.Response.Headers["X-Documentation"] = "example";
await next();
}
}
public class MiddlewareDemoController : BaseController
{
public IActionResult Show() => Content("Middleware reached the action.");
}
public class MiddlewareDemoProvider : Provider
{
public override void Boot(WebApplication app)
{
Route.AliasMiddleware<DocumentationHeader>("documentation-header");
Route.Get<MiddlewareDemoController>("/middleware-demo", c => c.Show)
.Middleware("documentation-header");
}
}Run dotblaze serve and request /middleware-demo. Expect HTTP 200, body Middleware reached the action., and X-Documentation: example. The provider is auto-discovered and registers both the alias and its route. Set headers before next: the action may start writing the response. For access control, return a refusal without calling next, or use the built-in auth/policy middleware rather than merely setting a header.
Introduction
Route middleware inspects or filters requests before they reach a controller, for example to send guests to the login page. In DotBlaze, route middleware is a class that implements IRouteMiddleware, is registered under a short alias, and is attached to routes by that alias, just like Laravel's ->middleware('auth').
Built-in Middleware
These aliases are available out of the box. csrf and trim-strings are already on every route through the web group.
Authenticate (auth)
auth lets authenticated users through. For everyone else:
- A request that wants JSON gets an empty
401 Unauthorized. - Any other request is redirected to the login page (the
loginkey inconfig/Auth.cs, default/login). ForGETrequests the original URL is remembered so the login action can send the user back withIntended()(see authentication).
Redirect If Authenticated (guest)
guest is for pages such as login and register. An authenticated user is redirected to the home key in config/Auth.cs (default /).
Ensure Email Is Verified (verified)
verified goes after auth. A user whose model implements IMustVerifyEmail and has not verified the email address is redirected to the verification.notice route; JSON requests get 403. See email verification.
Validate Signature (signed)
signed returns 403 unless the URL carries a valid, unexpired signature from URL.SignedRoute.
Validate CSRF Token (csrf)
In the web group. A POST, PUT, PATCH, or DELETE request without a valid CSRF token gets the 419 | Page Expired error page (JSON: { "message": "CSRF token mismatch." }). The api group uses csrf.api: the same check for cookie-authenticated writes, but not bearer-only or anonymous requests. See CSRF protection.
Trim Strings (trim-strings)
In the web and api groups. Removes leading and trailing whitespace from query string values, form fields, and string values in a JSON body before model binding, so " ali@example.com " is validated and saved as "ali@example.com". Fields named password, password_confirmation, and current_password (also as Password, PasswordConfirmation, user[current_password], ...) are left alone. Add more in a provider's Boot method:
TrimStrings.Except("Signature", "api_secret");Laravel's ConvertEmptyStringsToNull has no alias because ASP.NET Core model binding already does it: an empty field bound to a string? property is null.
Throttling Requests (throttle)
throttle limits how often a user (or, for guests, an IP address) may call a route. The parameters are the number of requests and the window in minutes:
Route.Post<EmailVerificationController>("/email/verification-notification", c => c.Send)
.Name("verification.send").Middleware("throttle:6,1"); // 6 per minuteOver the limit, the response is the 429 | Too Many Requests error page (JSON: { "message": "Too Many Attempts." }) with a Retry-After header in seconds. Every response through throttle carries X-RateLimit-Limit and X-RateLimit-Remaining.
Like Laravel, every throttle:max,minutes route shares one count per user. Give a route its own count with a third parameter, a key prefix: throttle:10,1,uploads.
For anything more, define a named limiter with RateLimiter.For in a provider's Boot method and use its name:
RateLimiter.For("uploads", request =>
Auth.User<User>() is { IsPremium: true } ? Limit.None() : Limit.PerMinute(10).By(Auth.Id()));
Route.Post<UploadController>("/uploads", c => c.Store).Middleware("throttle:uploads");| Method | |
|---|---|
Limit.PerSecond(max, seconds = 1), PerMinute(max), PerMinutes(minutes, max), PerHour(max), PerDay(max) | The window. |
.By(key) | What to count per. Default: the user's id, or the IP address for guests. By("everyone") makes one count for all. |
Limit.None() | No limit for this request. |
.WithResponse(context => ...) | Write your own 429 response. |
The api limiter (60 requests per minute per user or IP address) is defined out of the box and used by the api group; call RateLimiter.For("api", ...) to change it. Counts are kept by the RateLimiter in the cache, so with the redis cache store they are shared by every server.
Cache Headers (cache.headers)
cache.headers sets Cache-Control on successful GET and HEAD responses, with directives separated by semicolons like Laravel's. With etag, it also adds an ETag computed from the body, and answers 304 Not Modified (without a body) when the browser sends the same tag in If-None-Match:
Route.Get<Api.PostController>("/posts/{post}", c => c.Show).Middleware("cache.headers:public;max_age=60;etag");The directives are public, private, no_cache, no_store, must_revalidate, immutable, max_age=N, and s_maxage=N.
Confirm Password (password.confirm)
Asks the logged-in user for their password again unless they confirmed it recently. See Password Confirmation.
Token Abilities (abilities, ability)
For API tokens: abilities:posts:create,posts:delete requires every ability, ability:posts:delete,admin any of them. Requests with the login cookie pass.
Laravel Middleware Without an Alias
Several of Laravel's default middleware are covered by ASP.NET Core or by DotBlaze itself:
| Laravel | In DotBlaze |
|---|---|
EncryptCookies, AddQueuedCookiesToResponse | The login, remember-me, flash data, and CSRF cookies are protected with Data Protection. Encrypt your own cookie values with Crypt. |
StartSession, ShareErrorsFromSession | The session is started for every request, lazily; flash data and validation errors use TempData and are available in every view, see responses. |
ConvertEmptyStringsToNull | Model binding (see above). |
SubstituteBindings | Route model binding. |
ValidatePostSize | Kestrel's request body limit (30 MB by default, Kestrel:Limits:MaxRequestBodySize). |
TrustProxies, TrustHosts | Global middleware registered with services.AddTrustProxies(...) then services.AddTrustHosts(...) in a provider's Register. See deployment. |
HandleCors | ASP.NET Core's AddCors/UseCors, in a provider. |
PreventRequestsDuringMaintenance | Built in: maintenance mode (dotblaze down) runs before routing for every request. |
Authorize (can:update,post) | .Can("update", "post") on the route, see authorization. |
Defining Middleware
Implement IRouteMiddleware. Call next() to pass the request on; return without calling it to short-circuit with your own response:
using SampleApp.Models;
namespace SampleApp.Middleware;
public sealed class EnsureAdmin : IRouteMiddleware
{
public async Task Handle(HttpContext context, Func<Task> next)
{
// Assumes the User model has an IsAdmin property.
if (Auth.User<User>()?.IsAdmin != true)
{
context.Response.StatusCode = StatusCodes.Status403Forbidden;
return;
}
await next();
}
}Code placed after await next() runs once the controller has produced its response.
A new instance is created for every request, and its constructor dependencies are resolved from the request's service container:
public sealed class LogRequests(ILogger<LogRequests> logger) : IRouteMiddleware
{
public async Task Handle(HttpContext context, Func<Task> next)
{
logger.LogInformation("{Method} {Path}", context.Request.Method, context.Request.Path);
await next();
}
}Middleware Parameters
Like Laravel's role:editor, a middleware can take parameters after its alias. Implement IParameterizedRouteMiddleware (or run dotblaze make:middleware EnsureRole --parameters); the text after the colon is split on commas and passed as parameters:
public sealed class EnsureRole : IParameterizedRouteMiddleware
{
public async Task Handle(HttpContext context, Func<Task> next, string[] parameters)
{
// Assumes the User model has a Role property.
if (!parameters.Contains(Auth.User<User>()?.Role))
{
context.Response.StatusCode = StatusCodes.Status403Forbidden;
return;
}
await next();
}
}Route.AliasMiddleware<EnsureRole>("role");
Route.Get<ReportController>("/reports", c => c.Index).Middleware("auth", "role:admin,editor"); // ["admin", "editor"]
Route.Middleware("auth", "role:admin").Group(() => { ... });Spaces around the values are trimmed. Used without a colon ("role"), the middleware receives an empty array. Passing parameters to a middleware that does not implement IParameterizedRouteMiddleware throws an InvalidOperationException when the application starts, like an unknown alias.
Registering Middleware
Middleware Aliases
Give your middleware an alias with Route.AliasMiddleware in a service provider's Boot method:
public class AppServiceProvider : Provider
{
public override void Boot(WebApplication app)
{
Route.AliasMiddleware<EnsureAdmin>("admin");
}
}Routes are mapped after every provider has booted, so the alias may be registered in any provider regardless of order. Using an alias that was never registered throws an InvalidOperationException ("Unknown route middleware") when the application starts.
Assigning Middleware to Routes
Attach middleware to a single route or to a group:
Route.Get<ReportController>("/reports", c => c.Index).Middleware("auth", "admin");
Route.Middleware("auth").Group(() =>
{
Route.Resource<PostController>("/posts", parameter: "post");
});Middleware runs in the order listed, outer group first, then the route's own .Middleware(...).
Middleware Groups
A group is a name for several middleware, used like an alias. Two are built in:
| Group | Middleware | Used by |
|---|---|---|
web | trim-strings, csrf | Every route, unless it names web or api |
api | trim-strings, csrf.api, throttle:api | Routes that name it, normally those in routes/api.cs |
Group middleware runs first, in the group's order, then the route's own. A middleware listed twice (by a group and a route) runs once. Change the groups or define your own in a provider's Boot method:
Route.PushMiddlewareToGroup("web", "locale"); // add at the end
Route.PrependMiddlewareToGroup("api", "force-json"); // add at the start
Route.MiddlewareGroup("admin", "auth", "verified", "role:admin");
Route.Middleware("admin").Prefix("admin").Group(() => { ... });dotblaze route:list shows each route's groups and middleware.
Excluding Middleware
WithoutMiddleware leaves out middleware a route would get from its groups, by alias:
Route.Post<WebhookController>("/webhooks/stripe", c => c.Stripe).WithoutMiddleware("csrf");
Route.WithoutMiddleware("trim-strings").Group(() => { ... });Global Middleware
There is no DotBlaze API for global middleware. Because DotBlaze runs on ASP.NET Core, you can add ordinary ASP.NET Core middleware with app.Use(...) in a provider's Boot method. It is added after DotBlaze's own pipeline, so it runs after routing, authentication, and route middleware, just before the controller:
public override void Boot(WebApplication app)
{
app.Use(async (context, next) =>
{
context.Response.Headers["X-Frame-Options"] = "DENY";
await next(context);
});
}The Request Pipeline
For reference, this is the order in which DotBlaze handles a request:
- The developer exception page, in debug mode only (see error handling).
- Static files from
wwwroot, then files of thepublicdisk at its relativeurl,/storageby default (see file storage). - HTTP method override from the
_methodform field (see method spoofing). - The exception handler: a missing bound model becomes a
404,Abort(...)its status, and other exceptions a500page outside debug mode. - Routing, session-backed authentication (the
.dotblaze.sessioncookie), and loading the current user. - Route middleware: the route's groups (
web:trim-strings,csrf; orapi), then its own (auth,verified,throttle, your aliases). - MVC: model binding, then filters, including form request validation and
.Canchecks, then your controller action.
Because csrf is in the web group, it runs before auth: a guest posting without a token gets 419, like in Laravel.
Not Yet Available
NOTE
- There is no
can:update,postmiddleware alias; use.Can("update", "post")on the route instead (see authorization), which runs after model binding. - Global middleware has no DotBlaze API; add it to a group, or use
app.Use(...)as shown above.