Skip to content

Controllers ​

Introduction ​

Controllers group related request handling into one class. DotBlaze controllers are ordinary ASP.NET Core MVC controllers. Extending DotBlaze.BaseController (which extends MVC's Controller) adds Laravel-style redirect helpers such as Back() and Intended(). Controllers live in app/Http/Controllers.

Writing Controllers ​

Basic Controllers ​

csharp
using Microsoft.AspNetCore.Mvc;

namespace DotBlazeApp.Controllers;

public class HomeController : BaseController
{
    public IActionResult Index() => View(model: Config.Get<string>("app.name"));
}

Point a route at the action:

csharp
Route.Get<HomeController>("/", c => c.Index).Name("home");

Actions are public instance methods that return an IActionResult (or Task<IActionResult>). Everything MVC offers, such as View(), Json(), Content(), and StatusCode(), is available, plus the helpers described in responses.

Controller Namespace ​

The templates put controllers in the DotBlazeApp.Controllers namespace, not DotBlazeApp.Http.Controllers, even though the files live in app/Http/Controllers. A namespace segment called Http would hide the Http client facade inside your controllers.

Resource Controllers ​

A controller with the seven conventional actions can be registered with a single resource route. This illustrates a server-rendered version of the sample blog (the current repository sample uses live components for its list/form):

csharp
using Microsoft.AspNetCore.Mvc;
using SampleApp.Models;
using SampleApp.Notifications;
using SampleApp.Requests;

namespace SampleApp.Controllers;

public class PostController : BaseController
{
    public async Task<IActionResult> Index() =>
        View(await Post.Scope(Post.Latest).With(p => p.User).Paginate(10));

    public IActionResult Create() => View(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 });
        await Auth.User<User>()!.Notify(new PostPublished { Post = post });
        return RedirectRoute("posts.show", new { post = post.Id }).With("status", "Post created.");
    }

    public async Task<IActionResult> Show(Post post)
    {
        await post.Load(p => p.User);
        return View(post);
    }

    public async Task<IActionResult> Edit(Post post)
    {
        await Authorize("update", post);   // PostPolicy.Update; 403 otherwise
        return View(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.");
    }
}
csharp
Route.Middleware("auth").Group(() =>
{
    Route.Resource<PostController>("/posts", parameter: "post");
});

Authorize("update", post) checks the PostPolicy with the Gate and ends the request with 403 when it is denied (Laravel's $this->authorize()). MVC's Forbid() also returns 403 with the session authentication scheme.

Action Parameters ​

Action parameters are filled by MVC model binding, with two DotBlaze additions:

  • Route parameters bind by name: {id} → long id.
  • Models bind from the route parameter with the same name and return 404 when not found: {post} → Post post. See route model binding.
  • Form requests (classes deriving from FormRequest<T>) are bound from the form and validated before the action runs. See validation.
  • Uploaded files bind to IFormFile parameters, or read them with Request.File("name").

Dependency Injection ​

Controllers are created by the ASP.NET Core container, so constructor injection works for any registered service:

csharp
public class ReportController(ILogger<ReportController> logger) : BaseController
{
    public IActionResult Index()
    {
        logger.LogInformation("Report viewed");
        return View();
    }
}

Most framework services are also reachable through facades (Auth, Config, Storage, Http, ...), which need no injection.

Complete Example and Required Files ​

Use the complete CRUD controller with its request and policy, model and migration, and three Blade views. Those sections define every type that the controller uses.

To add a JSON detail endpoint to that same controller, add this method:

csharp
public async Task<IActionResult> Details(Post post)
{
    await post.Load(value => value.User);
    return Json(new
    {
        post.Id,
        post.Title,
        post.Body,
        author = post.User?.Name,
    });
}

Add Route.Get<Blog.Controllers.PostController>("/post-details/{post}", c => c.Details).Middleware("auth"); inside Web.Map(). After creating a post, open /post-details/1 using its actual ID. Expected: camelCase JSON with id, title, body, and author. Selecting response fields explicitly avoids accidentally exposing additional model fields.