Skip to content

HTTP Responses ​

Creating Responses ​

Controller actions return ASP.NET Core IActionResult values. DotBlaze adds redirect helpers with Laravel-style flash data on BaseController; everything else is standard MVC.

Views ​

csharp
public IActionResult Create() => View(new Post());
public IActionResult ShowLogin() => View("Login");

See views.

JSON Responses ​

Json(...) and Ok(...) serialize with ASP.NET Core's web defaults (camelCase property names). DotBlaze configures the serializer for models: [Hidden] properties such as a password are left out, computed properties are only included when marked [Appends], and reference cycles between related models are ignored:

csharp
public async Task<IActionResult> Show(Post post)
{
    await post.Load(p => p.User);
    return Json(post);   // { "id": 1, "title": "...", "excerpt": "...", "user": { "id": 1, "name": "Ali", ... } }
}

See serialization.

Other Responses ​

csharp
return Content("Hello");                                  // text/plain
return StatusCode(StatusCodes.Status403Forbidden);
return NotFound();
return File(bytes, "application/pdf", "invoice.pdf");      // download

To set a header or cookie, use Response before returning:

csharp
Response.Headers["X-Version"] = "1";
Response.Cookies.Append("theme", "dark");

Redirects ​

BaseController provides four redirect helpers. Each returns a RedirectWith result that you can chain flash data on, and each issues a 302 Found.

csharp
return RedirectTo("/posts");

Redirecting Back ​

Back() redirects to the previous page, taken from the Referer header. The referer is only used when it points at the same host; otherwise, or when there is no referer, the fallback (default /) is used:

csharp
return Back();
return Back(fallback: "/posts");

Redirecting to Named Routes ​

csharp
return RedirectRoute("posts.index");
return RedirectRoute("posts.show", new { post = post.Id });

An unknown route name or missing parameter throws an InvalidOperationException.

Redirecting to the Intended URL ​

When the auth middleware sends a guest to the login page, it remembers the URL they asked for. After logging in, Intended() sends them there, or to the fallback if nothing was remembered (or the remembered URL is not local):

csharp
if (await Auth.Attempt(new { request.Email, request.Password }, request.Remember))
    return Intended("/posts");

Flash Data ​

Redirecting With Flashed Data ​

.With(key, value) stores a value for the next request, like Laravel's ->with():

csharp
return RedirectRoute("posts.show", new { post = post.Id }).With("status", "Post created.");

Flash data is stored in ASP.NET Core TempData, so read it with TempData[key]. The sample layout shows a status banner like this:

html
@if (TempData["status"] is string status)
{
    <div class="mb-4 rounded bg-green-100 p-3 text-green-800">@status</div>
}

Strings, int, bool, and null are stored as is. Any other value is converted with ToString().

Errors and Old Input ​

.WithErrors(...) flashes validation errors and .WithInput() flashes the current form input (without passwords), the same data a failed form request produces:

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

WithErrors accepts an anonymous object or dictionary; each value may be a string or a list of strings. Errors are merged with any already flashed in the same request. Views read them with @Error, @Errors, @HasErrors(), and @Old (see displaying validation errors).

How Long Flash Data Lives ​

Flash data (errors, old input, and values set with .With(...)) lives for exactly one MVC request after the one that stored it, then it is removed, whether or not anything read it. In the usual flow (redirect, then render a page) it is shown once. Reading it with @Old, @Error, @Errors, @HasErrors(), or TempData["status"] does not extend its life.

NOTE

url.intended, the URL remembered by the auth middleware, is not flash data. It stays until Intended() reads it.

TempData uses ASP.NET Core's default cookie provider, so keep flashed values small.

Complete Example: Download a Text File ​

Create this controller in the Blog template:

csharp
// app/Http/Controllers/TextDownloadController.cs
using System.Text;
using DotBlaze;
using Microsoft.AspNetCore.Mvc;

namespace Blog.Controllers;

public class TextDownloadController : BaseController
{
    public IActionResult Show()
    {
        Response.Headers["Cache-Control"] = "no-store";
        var bytes = Encoding.UTF8.GetBytes("Hello from DotBlaze.\n");
        return File(bytes, "text/plain; charset=utf-8", "hello.txt");
    }
}

Add Route.Get<Blog.Controllers.TextDownloadController>("/download-example", c => c.Show); inside Web.Map(). Run dotblaze serve and open /download-example. Expected: HTTP 200, a Content-Disposition attachment named hello.txt, and a single line of text. Headers are assigned before the response body starts.

For a complete redirect/flash cycle, use the blog's Store and Show actions and view. Its HTTP test asserts the redirect and status separately instead of following redirects before inspecting the 302 response.