Skip to content

HTTP Requests ​

Introduction ​

DotBlaze does not wrap the request. Inside a controller, Request is ASP.NET Core's HttpRequest, and DotBlaze adds a few Laravel-style extension methods to it (WantsJson(), File()). For validated input, prefer a form request.

Accessing the Request ​

Binding Input to Parameters ​

The simplest way to read input is to declare it as an action parameter. MVC binds route values, query string values, and form fields by name (case-insensitive):

csharp
// GET /search?term=dotblaze&page=2
public IActionResult Search(string term, int page = 1) => Content($"{term} page {page}");

A form request binds every field in one object and validates it:

csharp
public async Task<IActionResult> Store(PostRequest request)
{
    // request.Title and request.Body are valid here
}

NOTE

Form fields must use the property name (PasswordConfirmation), not a snake_case variant (password_confirmation). Field names are matched case-insensitively, but underscores are not ignored during binding.

Reading the Request Directly ​

Everything else is available on HttpRequest:

csharp
var path   = Request.Path;                          // "/posts/1"
var method = Request.Method;                        // "POST" (after _method override)
var page   = Request.Query["page"].ToString();
var title  = Request.Form["Title"].ToString();      // form posts only
var agent  = Request.Headers.UserAgent.ToString();
var theme  = Request.Cookies["theme"];
var post   = RouteData.Values["post"];

Content Negotiation ​

Request.WantsJson() returns true when the Accept header contains application/json or the request has X-Requested-With: XMLHttpRequest:

csharp
public IActionResult Show(Post post) =>
    Request.WantsJson() ? Json(post) : View(post);

DotBlaze uses the same check to decide between a redirect and a JSON response when validation fails, and between a login redirect and a 401 in the auth middleware.

Old Input ​

When validation fails, DotBlaze flashes the submitted form fields so the form can be filled again. Read them in a view with @Old:

html
<input type="text" name="Title" value="@(Old("Title") ?? Model.Title)" />
<input type="text" name="Title" value="@Old("Title", Model.Title)" />

Fields whose name contains password (any case), the CSRF token, and _method are never flashed. To flash input yourself, call .WithInput() on a redirect:

csharp
return Back().WithErrors(new { Email = "These credentials do not match our records." }).WithInput();

See validation for details.

Files ​

Retrieving Uploaded Files ​

Request.File(name) returns the uploaded IFormFile, or null when the request is not a form post or the field is empty:

csharp
var avatar = Request.File("avatar");

if (avatar is not null && avatar.Length > 0)
{
    // ...
}

You may also take an IFormFile action parameter. Remember that the form needs enctype="multipart/form-data".

Storing Uploaded Files ​

Store saves the file on a disk under a random 40-character name (keeping a safe extension) and returns its path relative to the disk:

csharp
var path = await Request.File("avatar")!.Store("avatars", disk: "public");
// "avatars/3fK...x9Q.png"

var url = Storage.Disk("public").Url(path);   // "/storage/avatars/3fK...x9Q.png"

Use StoreAs to choose the file name yourself. See storing uploaded files.

Complete Example: Validated Input ​

Use the complete PostRequest, controller, and form to see how names flow from HTML to validated C# properties. The form sends Title and Body; the action explicitly assigns only those properties, while deriving UserId from the signed-in user.

For a standalone query-string example, create:

csharp
// app/Http/Controllers/SearchInputController.cs
using DotBlaze;
using Microsoft.AspNetCore.Mvc;

namespace Blog.Controllers;

public class SearchInputController : BaseController
{
    public IActionResult Show(string term = "", int page = 1)
    {
        if (!ModelState.IsValid || page < 1 || term.Length > 100)
            return BadRequest(new { message = "Use a positive page and at most 100 characters." });
        return Json(new { term = term.Trim(), page });
    }
}

Add Route.Get<Blog.Controllers.SearchInputController>("/search-input", c => c.Show); inside Web.Map(). Run dotblaze serve; /search-input?term=hello&page=2 returns {"term":"hello","page":2}. page=abc or page=0 returns 400. Ordinary MVC parameters need their own validity checks; form requests handle their declared validation rules automatically.