Routing
- Basic Routing
- Complete Example
- Route Parameters
- Named Routes
- Route Groups
- Route Model Binding
- Form Method Spoofing
- Not Yet Available
Basic Routing
DotBlaze routes map a URL and an HTTP verb to an action on an MVC controller. Instead of a string such as Laravel's [PostController::class, 'show'], the action is a lambda that points at a method group, so a typo in the action name is a compile error:
Route.Get<PostController>("/posts/{post}", c => c.Show);The lambda is never executed against a real controller; DotBlaze only reads which method it names. Under the hood every route becomes an ASP.NET Core conventional MVC endpoint, so controllers are plain MVC controllers (see controllers). Each route maps to exactly the controller type it names, so controllers in different namespaces may share a name (PostController and Api.PostController).
The Default Route Files
Routes are defined in C# in routes/web.cs and routes/api.cs, static classes that are called while the application boots. Routes in web.cs get the web middleware group (CSRF protection, trimmed input); routes in api.cs are under /api and get the api group instead (CSRF for cookie-authenticated writes, rate limited). The application template registers both from app/Providers/RouteServiceProvider.cs:
// routes/web.cs
using DotBlazeApp.Controllers;
namespace DotBlazeApp.Routes;
public static class Web
{
public static void Map()
{
Route.Get<HomeController>("/", c => c.Index).Name("home");
}
}// app/Providers/RouteServiceProvider.cs
using DotBlazeApp.Routes;
namespace DotBlazeApp.Providers;
public class RouteServiceProvider : Provider
{
public override void Boot(WebApplication app)
{
Web.Map();
Api.Map();
}
}// routes/api.cs
public static class Api
{
public static void Map()
{
Route.Prefix("api").Middleware("api").Name("api.").Group(() =>
{
Route.Get<Controllers.Api.PostController>("/posts", c => c.Index).Name("posts.index");
});
}
}The groups are decided by the middleware, not by the file: a route is in web unless it (or one of its groups) names web or api. Routes may be registered from the Boot method of any service provider. They are mapped to endpoints after every provider has booted.
NOTE
Microsoft.AspNetCore.Routing also contains a type called Route. The application template adds <Using Include="DotBlaze.Route" Alias="Route" /> to the project file so that Route always means DotBlaze's facade.
Available Router Methods
Route.Get<TController>(pattern, c => c.Action); // GET and HEAD
Route.Post<TController>(pattern, c => c.Action);
Route.Put<TController>(pattern, c => c.Action);
Route.Patch<TController>(pattern, c => c.Action);
Route.Delete<TController>(pattern, c => c.Action);Each method returns a route definition you can chain .Name(...) and .Middleware(...) on:
Route.Post<AuthController>("/logout", c => c.Logout).Name("logout").Middleware("auth");The action may be synchronous or asynchronous. An Async suffix is dropped from the action name (c => c.IndexAsync maps to the Index action), and an [ActionName] attribute on the method is respected.
Resource Routes
Route.Resource registers the conventional CRUD routes for a controller in one call, like Laravel's Route::resource:
Route.Resource<PostController>("/posts", parameter: "post");| Verb | URI | Action | Route Name |
|---|---|---|---|
| GET | /posts | Index | posts.index |
| GET | /posts/create | Create | posts.create |
| POST | /posts | Store | posts.store |
| GET | /posts/{post} | Show | posts.show |
| GET | /posts/{post}/edit | Edit | posts.edit |
| PUT | /posts/{post} | Update | posts.update |
| PATCH | /posts/{post} | Update | (unnamed) |
| DELETE | /posts/{post} | Destroy | posts.destroy |
Only actions that exist as public methods on the controller are registered, so a controller without Edit simply has no edit route. The route name prefix is the last path segment (/admin/users gives users.index, ...). The parameter argument is optional: by default it is the singular form of the last segment (/posts → {post}, /categories → {category}).
Listing Your Routes
The route:list command prints every registered route with its verbs, URI, name, action, and middleware:
dotblaze route:listRoute Parameters
Route patterns use the ASP.NET Core route template syntax. Segments in braces are route parameters and are passed to action parameters with the same name:
Route.Get<UserController>("/users/{id}", c => c.Show);public class UserController : BaseController
{
public IActionResult Show(long id) => Content($"User {id}");
}Because the pattern is handed to ASP.NET Core unchanged, its constraints and optional parameters also work, for example {id:int} or {page?}.
Named Routes
Name a route with .Name(...) and generate its URL with Url.Route in a controller or @Route(...) in a view:
Route.Get<PostController>("/posts/{post}", c => c.Show).Name("posts.show");// In a controller
var url = Url.Route("posts.show", new { post = 1 }); // "/posts/1"
return RedirectRoute("posts.show", new { post = post.Id });<a href="@Route("posts.show", new { post = post.Id })">@post.Title</a>Url.Route throws an InvalidOperationException when the route does not exist or a required parameter is missing, so a broken link fails loudly instead of rendering an empty href. For absolute URLs outside a request (queued mail) and signed URLs, use the URL facade.
To authorize a route with the Gate after model binding, add .Can(...): Route.Get<PostController>("/posts/{post}/edit", c => c.Edit).Can("update", "post"). See authorization.
Inspecting the Current Route
RouteIs checks the name of the route that matched the request, like Laravel's request()->routeIs(). A * matches any characters, dots included, and any of several patterns may match:
<a href="{{ Route("dashboard") }}" @class(("is-active", RouteIs("dashboard")))>Dashboard</a>
<a href="{{ Route("posts.index") }}" @class(("is-active", RouteIs("posts.*")))>Posts</a>
<a href="{{ Route("settings") }}" @class(("is-active", RouteIs("settings", "two-factor.*")))>Settings</a>Prefer it to comparing Context.Request.Path: it still works when a URL changes, covers /posts/5/edit with posts.*, and ignores the path base and trailing slashes.
Request.RouteIs("admin.*"); // in a controller or middleware (an HttpRequest extension)
Request.RouteName(); // "admin.users.index", or null
Route.Is("admin.*"); // anywhere during a request, like Route::is()
Route.CurrentRouteName(); // like Route::currentRouteName()Matching is case-sensitive, as in Laravel. A route without .Name(...), or a request no route matched (a 404 page), matches no pattern. A live component re-rendering after an action runs in its own /_live/update request, which has no route name, so check the route in the layout or page around the component, or pass the result in as a property.
Route Groups
Groups share middleware, a URI prefix, or a name prefix across many routes. Start a group with Route.Middleware, Route.Prefix, or Route.Name, chain the others, and finish with .Group(...):
Route.Middleware("auth").Prefix("/admin").Name("admin.").Group(() =>
{
Route.Get<UserController>("/users", c => c.Index).Name("users.index"); // GET /admin/users, "admin.users.index"
});Groups can be nested; prefixes, name prefixes, and middleware of the outer group are applied first.
There is also a shorthand that takes a prefix and middleware together:
Route.Group("/admin", ["auth", "admin"], () =>
{
Route.Resource<UserController>("/users");
});Middleware
Route.Middleware("auth").Group(() =>
{
Route.Post<AuthController>("/logout", c => c.Logout).Name("logout");
Route.Resource<PostController>("/posts", parameter: "post");
});Group middleware runs before middleware added to an individual route with .Middleware(...). See middleware for the built-in auth and guest aliases and how to write your own.
Route Prefixes
Route.Prefix("/admin").Group(() =>
{
Route.Get<DashboardController>("/dashboard", c => c.Index); // GET /admin/dashboard
});Route Name Prefixes
The name prefix is prepended as is, so include the trailing dot yourself:
Route.Name("admin.").Group(() =>
{
Route.Get<UserController>("/users", c => c.Index).Name("users"); // "admin.users"
});Resource route names get the prefix too (admin.users.index, ...).
Route Model Binding
When an action parameter is a model (a class deriving from Model<T>), DotBlaze loads it by primary key from the route parameter with the same name. If no row matches, the response is a 404 Not Found:
Route.Get<PostController>("/posts/{post}", c => c.Show).Name("posts.show");public async Task<IActionResult> Show(Post post)
{
await post.Load(p => p.User);
return View(post);
}The parameter name must match the route parameter name ({post} → Post post). The value is always looked up by primary key (FindOrFail); binding by another column, such as Laravel's {post:slug}, is not supported. See models for defining models.
Form Method Spoofing
HTML forms can only send GET and POST. To reach a PUT, PATCH, or DELETE route from a form, post a hidden _method field. The @Method view helper writes it for you:
<form method="post" action="@Route("posts.update", new { post = Model.Id })">
@Csrf()
@Method("PUT")
...
</form>The override is applied to POST requests with form content before routing, so the route above is matched as a PUT. Do not forget @Csrf(); see CSRF protection.
Not Yet Available
NOTE
There are no fallback routes, redirect routes (Route::redirect), or view routes (Route::view). For rate limiting, see the throttle middleware.
Complete Example
The blog walkthrough supplies the full PostController, Post, PostRequest, policy, and views behind this registration. In its existing routes/web.cs, inside Web.Map():
Route.Middleware("auth").Group(() =>
{
Route.Resource<Blog.Controllers.PostController>("/posts", parameter: "post");
});Run dotblaze route:list. Expect eight verb/path mappings for the seven resource actions (both PUT and PATCH call Update). Visit /posts/create while signed in; the form submits to the named posts.store route. A missing /posts/999999 returns 404, while a guest is redirected to login before reaching the controller. Do not register the same resource twice when combining examples.
The complete HTTP test checks route binding, redirects, validation, and forbidden access together. A route is usable only after its containing method is called from a provider; creating a file alone does not register it.