Skip to content

Complete Application Example ​

Sample Conventions ​

This guide builds a small authenticated blog from a fresh template: list, create, read, edit, and delete posts. It includes the database schema, validation, ownership checks, views, routes, and HTTP tests. Use it as the shared foundation for examples on the topic pages.

  • Runtime: .NET 10 SDK. Node.js and npm build the template's frontend.
  • Application name: Blog. Replace Blog consistently if your project has another namespace.
  • Paths: relative to the application directory unless a step says otherwise.
  • Imports: the template supplies global DotBlaze, DotBlaze.Support, static DotBlaze.Support.Functions, and the Route = DotBlaze.Route alias. Complete C# files below also show their local imports.
  • Execution context: facade/model calls run in a controller, command, job, seeder, or TestApp.Run. A bare C# console application has no DotBlaze service scope.
  • Reference snippets versus complete examples: API-reference snippets illustrate one operation and may use a model from the surrounding section. A complete example names its files and supplies its application-specific types. Separate examples are alternatives; do not paste several definitions of Post, Web, or a config section into the same project.
  • Configuration: edit an existing config/provider/route class when a page says to add a member or registration. Creating a second AppConfig or a second Web.Map does not merge it with the original.
  • Async: await database, network, queue, and storage calls. A fluent builder alone may not perform the operation.
  • Secrets: values such as API keys are environment variables. Example credentials and seed users are for a local learning application.

The documentation index groups every topic. The repository sample and its tests demonstrate a larger application with live components, notifications, broadcasting, and dashboards.

Create the Application ​

Run from the directory that will contain your application:

shell
dotnet new install DotBlaze.Templates
dotnet tool install --global DotBlaze.Cli
dotblaze new Blog
cd Blog
dotblaze make:auth
npm install
npm run build

If the tool is already installed, use dotnet tool update --global DotBlaze.Cli. dotblaze new creates .env with an application key. Keep the generated User model, user migration, auth scaffolding, configuration, and providers.

The generated entry point is already complete:

csharp
// Program.cs
var app = DotBlaze.Application.Create(args);
app.Run();

public partial class Program;

Use the template's SQLite configuration for this walkthrough. No external database, Redis, or email server is required. The posts routes below use auth; they do not require email verification.

Model and Migration ​

Create these two files. UserId is assigned by the server, so it is deliberately not fillable.

csharp
// app/Models/Post.cs
using DotBlaze;

namespace Blog.Models;

public class Post : Model<Post>
{
    public long Id { get; set; }
    public long UserId { get; set; }
    [Fillable] public string Title { get; set; } = "";
    [Fillable] public string Body { get; set; } = "";
    public DateTime? CreatedAt { get; set; }
    public DateTime? UpdatedAt { get; set; }
    public User? User { get; set; }
}
csharp
// database/migrations/CreatePostsTable.cs
using DotBlaze;

namespace Blog.Database.Migrations;

[Migration("2026_11_27_000000_create_posts_table")]
public class CreatePostsTable : Migration
{
    public override void Up() => Schema.Create("posts", table =>
    {
        table.Id();
        table.ForeignId("user_id").Constrained().CascadeOnDelete();
        table.String("title");
        table.Text("body");
        table.Timestamps();
    });

    public override void Down() => Schema.DropIfExists("posts");
}

The migration ID must sort after the template's users migration. Model properties map to snake_case columns; long Id matches table.Id(). The database enforces the user foreign key. Deleting a user also deletes that user's posts because this example explicitly requests cascading deletion.

Validation and Authorization ​

csharp
// app/Http/Requests/PostRequest.cs
using DotBlaze;
using FluentValidation;

namespace Blog.Requests;

public class PostRequest : FormRequest<PostRequest>
{
    public string Title { get; set; } = "";
    public string Body { get; set; } = "";

    public override void Rules(RuleSet<PostRequest> rules)
    {
        rules.Field(value => value.Title).NotEmpty().MaximumLength(255);
        rules.Field(value => value.Body).NotEmpty().MaximumLength(10000);
    }
}
csharp
// app/Policies/PostPolicy.cs
using Blog.Models;
using DotBlaze;

namespace Blog.Policies;

public class PostPolicy : Policy<Post>
{
    public bool Update(User user, Post post) => user.Id == post.UserId;
    public bool Delete(User user, Post post) => user.Id == post.UserId;
}

The form-request filter validates before the action runs. The policy is discovered automatically. All signed-in users can read posts in this example; only their author can edit or delete them.

Controller and Routes ​

csharp
// app/Http/Controllers/PostController.cs
using Blog.Models;
using Blog.Requests;
using DotBlaze;
using Microsoft.AspNetCore.Mvc;

namespace Blog.Controllers;

public class PostController : BaseController
{
    public async Task<IActionResult> Index() =>
        View(await Post.OrderByDesc(post => post.Id).Take(20).Get());

    public IActionResult Create() => View("Form", new Post());

    public async Task<IActionResult> Store(PostRequest request)
    {
        var post = new Post { UserId = (long)Auth.Id()! };
        await post.Update(new { request.Title, request.Body });
        return RedirectRoute("posts.show", new { post = post.Id })
            .With("status", "Post created.");
    }

    public IActionResult Show(Post post) => View(post);

    public async Task<IActionResult> Edit(Post post)
    {
        await Authorize("update", post);
        return View("Form", post);
    }

    public async Task<IActionResult> Update(Post post, PostRequest request)
    {
        await Authorize("update", post);
        await post.Update(new { request.Title, request.Body });
        return RedirectRoute("posts.show", new { post = post.Id })
            .With("status", "Post updated.");
    }

    public async Task<IActionResult> Destroy(Post post)
    {
        await Authorize("delete", post);
        await post.Delete();
        return RedirectRoute("posts.index").With("status", "Post deleted.");
    }
}

Add using Blog.Controllers; to routes/web.cs if needed. Add the following inside its existing Web.Map() method, keeping the generated home and auth routes:

csharp
Route.Middleware("auth").Group(() =>
{
    Route.Resource<PostController>("/posts", parameter: "post");
});

RouteServiceProvider.Boot already calls Web.Map(). Do not add a second call. {post} binds to the Post post argument by primary key; an unknown key produces a 404. The route names are posts.index, posts.create, posts.store, posts.show, posts.edit, posts.update, and posts.destroy.

Blade Views ​

Keep the generated layout and _ViewImports.cshtml. Create these three views. This uses the controller-name convention: PostController resolves views under resources/views/post.

html
<!-- resources/views/post/Index.blade.html -->
@model DotBlaze.Support.Collection<Blog.Models.Post>
@extends('layouts.app')
@section('title', "Posts")
@section('content')
    <h1>Latest 20 posts</h1>
    @if (TempData["status"] is string status)
        <p role="status">{{ status }}</p>
    @endif
    <a href="{{ Route('posts.create') }}">Create a post</a>
    @forelse (var post in Model)
        <article>
            <h2><a href="{{ Route('posts.show', new { post = post.Id }) }}">{{ post.Title }}</a></h2>
        </article>
    @empty
        <p>No posts yet.</p>
    @endforelse
@endsection
html
<!-- resources/views/post/Form.blade.html -->
@model Blog.Models.Post
@extends('layouts.app')
@section('title', Model.Id == 0 ? "Create post" : "Edit post")
@section('content')
    <h1>{{ Model.Id == 0 ? "Create post" : "Edit post" }}</h1>
    <form method="post"
          action="{{ Model.Id == 0 ? Route('posts.store') : Route('posts.update', new { post = Model.Id }) }}">
        @csrf
        @if (Model.Id != 0)
            @method('PUT')
        @endif
        <label for="title">Title</label>
        <input id="title" name="Title" value="{{ Old('Title', Model.Title) }}"
               maxlength="255" required aria-describedby="title-error" />
        <p id="title-error" role="alert">{{ Error('Title') }}</p>
        <label for="body">Body</label>
        <textarea id="body" name="Body" maxlength="10000"
                  required aria-describedby="body-error">{{ Old('Body', Model.Body) }}</textarea>
        <p id="body-error" role="alert">{{ Error('Body') }}</p>
        <button type="submit">Save</button>
    </form>
    <a href="{{ Route('posts.index') }}">Back to posts</a>
@endsection
html
<!-- resources/views/post/Show.blade.html -->
@model Blog.Models.Post
@extends('layouts.app')
@section('title', Model.Title)
@section('content')
    @if (TempData["status"] is string status)
        <p role="status">{{ status }}</p>
    @endif
    <h1>{{ Model.Title }}</h1>
    <p style="white-space: pre-wrap">{{ Model.Body }}</p>
    @if (await Can("update", Model))
        <a href="{{ Route('posts.edit', new { post = Model.Id }) }}">Edit</a>
    @endif
    @if (await Can("delete", Model))
        <form method="post" action="{{ Route('posts.destroy', new { post = Model.Id }) }}">
            @csrf
            @method('DELETE')
            <button type="submit">Delete post</button>
        </form>
    @endif
    <a href="{{ Route('posts.index') }}">Back to posts</a>
@endsection

{{ ... }} escapes user content. @csrf protects every state-changing form. In Blade use {{ Old('Title') }} and @method('PUT'); the equivalent Razor syntax is @Old("Title") and @Method("PUT"). Hiding buttons is only a UI convenience: the controller enforces the policy even when someone sends a request directly.

Run the Application ​

From Blog:

shell
dotnet build
dotblaze migrate
dotblaze db:seed
dotblaze db:check
dotblaze route:list
dotblaze serve

Open the printed server URL and visit /login. The template seeder creates test@example.com with password password. Visit /posts, create a post, follow its detail page, edit it, then delete it.

ActionExpected result
Guest opens /postsRedirect to /login.
Signed-in user opens an empty list“No posts yet.”
Submit valid title/bodyRedirect to the new detail page; a row is saved.
Submit an empty title with browser validation bypassedRedirect back with a validation message and old input.
Send invalid JSON accepting JSON422 with field errors.
Send a web POST without a valid CSRF token419; no row is saved.
Another user edits/deletes the post403; the row remains unchanged.
Open a nonexistent post404.

The list intentionally shows the latest 20 posts. To add page navigation, follow pagination.

Automated HTTP Tests ​

Create a sibling project, not a nested folder inside Blog (the web project's default compile glob would include nested test files). From the parent of Blog:

shell
dotnet new xunit -n Blog.Tests --framework net10.0
dotnet add Blog.Tests reference Blog/Blog.csproj
dotnet add Blog.Tests package DotBlaze.Testing

Keep DotBlaze.Testing on the same version as DotBlaze. Use xUnit 2 for the test API below (xunit 2.9.3, xunit.runner.visualstudio 3.1.4, and Microsoft.NET.Test.Sdk 17.14.1 are the versions used by this repository).

csharp
// Blog.Tests/PostTest.cs
using Blog.Models;
using DotBlaze.Testing;
using Xunit;

namespace Blog.Tests;

public class PostTest
{
    [Fact]
    public async Task Author_can_create_edit_and_delete_but_another_user_cannot()
    {
        using var app = new TestApp<Program>();
        await app.RefreshDatabase();
        var owner = await app.Run(() => User.Factory().Create());
        var other = await app.Run(() => User.Factory().Create());
        var client = app.Client().ActingAs(owner);

        (await app.Client().Get("/posts")).AssertRedirect("/login");
        (await client.Get("/posts")).AssertOk().AssertSee("No posts yet.");
        (await client.Get("/posts/create")).AssertOk().AssertSee("Title");
        (await client.Post("/posts", new { Title = "First post", Body = "Hello" }))
            .AssertRedirect().AssertSessionHas("status", "Post created.");

        var post = await app.Run(() =>
            Post.Where(value => value.Title == "First post").FirstOrFail());
        await app.AssertDatabaseHas("posts", new { id = post.Id, user_id = owner.Id });
        (await client.Get($"/posts/{post.Id}")).AssertOk().AssertSee("Hello");
        (await client.Get($"/posts/{post.Id}/edit")).AssertOk().AssertSee("First post");

        (await app.Client().ActingAs(other).Put($"/posts/{post.Id}",
            new { Title = "Stolen", Body = "Changed" })).AssertForbidden();
        (await app.Client().ActingAs(other).Delete($"/posts/{post.Id}")).AssertForbidden();
        await app.AssertDatabaseHas("posts", new { id = post.Id, title = "First post" });

        (await client.PostJson("/posts", new { Title = "", Body = "Keep" }))
            .AssertJsonValidationErrors("Title");
        (await app.Client().ActingAs(owner).WithoutCsrfToken()
            .Post("/posts", new { Title = "Rejected", Body = "No token" })).AssertStatus(419);

        (await client.Put($"/posts/{post.Id}", new { Title = "Revised", Body = "Updated" }))
            .AssertRedirect($"/posts/{post.Id}");
        await app.AssertDatabaseHas("posts", new { id = post.Id, title = "Revised" });
        (await client.Delete($"/posts/{post.Id}")).AssertRedirect("/posts");
        await app.AssertModelMissing(post);
        (await client.Get($"/posts/{post.Id}")).AssertNotFound();
    }
}

Run from the parent directory:

shell
dotnet test Blog.Tests

TestApp uses an isolated SQLite file, the array mailer, memory cache, and synchronous queue. ActingAs authenticates a real saved user; it does not bypass policies. The test client supplies CSRF tokens unless explicitly disabled. RefreshDatabase drops the test database's tables; keep its default isolated connection.

Troubleshooting ​

SymptomCheck
Route is ambiguousKeep the template's DotBlaze.Route alias in the project file.
Http.Get resolves to a namespaceUse Blog.Controllers, not Blog.Http.Controllers; see structure.
“No service scope”Move facade calls into a framework entry point or TestApp.Run.
no such table: postsRun dotblaze migrate in the same application and environment as the server.
View not foundUse resources/views/post and matching Index, Form, and Show names; check case on Linux.
419 when submittingLoad the form on the same origin, retain its cookies, and submit @csrf's hidden field.
403 for the ownerCheck UserId was assigned from Auth.Id() and that the browser is signed in as that user.
Route not listedAdd the resource registration inside the existing Web.Map; check the provider calls it once.
A new field is ignoredUpdate the model, migration, request rules, and explicit controller assignment; [Fillable] is an allowlist.

Learning Map for AI Agents ​

Read in this order when implementing a feature:

  1. Configuration, structure, and lifecycle: discover where files live and when services exist.
  2. Routing, controllers, requests, and validation: follow input into an action.
  3. Authentication, authorization, and CSRF: preserve authentication, ownership, and form protection.
  4. Migrations, models, and relationships: match C# properties to the actual schema.
  5. Responses, views, and Blade: render or serialize the result.
  6. Testing, HTTP tests, and database tests: verify success, invalid input, missing rows, and a different user's access.

For an unfamiliar method, inspect its public signature under src, its use in samples/SampleApp, and its behavior in tests. Laravel similarity is a guide to concepts, not proof that a PHP method or package exists in DotBlaze. Check known gaps and each optional package's installation section before generating code.