← All guides
Development 2 min read

Binding forms safely in Razor Pages

Why you never bind entities, what Post-Redirect-Get is good for and how redirects don't become an open door – with examples from our framework.

  • ASP.NET Core
  • Razor Pages
  • Security

Never bind entities

If a page binds a database entity directly, an attacker can post every field the entity has – including IsAdmin or OwnerId . This is called over-posting and takes seconds to try with the browser's developer tools.

The fix is a dedicated input model that contains only the fields the form is allowed to edit. The service maps them onto the entity and checks authorisation while doing so.

public sealed class EditModel(IProjectService projects) : PageModel
{
    [BindProperty]
    public ProjectInput Input { get; set; } = new();

    public sealed class ProjectInput
    {
        [Required, StringLength(120)]
        public string Name { get; set; } = string.Empty;
    }
}

Post-Redirect-Get

A successful POST ends with a redirect, never with Page() . Otherwise a reload submits the form again – and in the worst case sends an email twice. Only on validation errors is the page re-rendered directly.

public async Task<IActionResult> OnPostAsync(CancellationToken cancellationToken)
{
    if (!ModelState.IsValid)
        return Page();

    await projects.RenameAsync(Id, Input.Name, cancellationToken);
    StatusMessage = "Gespeichert.";
    return RedirectToPage(new { Id });
}

Check redirects and query values

Everything that comes from the request is input – the URL included. A ReturnUrl parameter may only point to your own site, otherwise sign-in becomes a springboard for phishing. Numbers from the query are clamped, enums checked.

  1. Redirect only via LocalRedirect or after Url.IsLocalUrl .
  2. Check enums with Enum.IsDefined – the binder accepts any number.
  3. Use SupportsGet only for single, validated properties.
  4. Protect sign-in and password pages with rate limiting.