Search code examples
c#asp.net-corerazor

HTTP 400 on simple ASP.Net Core Razor page


I'm trying to create a simple "Hello world" ASP.Net Core 3.1 app, but trying to POST a form, I keep getting:

This page isn’t working. If the problem continues, contact the site owner.

HTTP ERROR 400

Steps to reproduce:

  1. MSVS2019 > New Project > ASP.Net Core Web Application, C#

  2. DELETE the boilerplate, auto-generated code in Pages\*, substitute my own Index.cshtml and Index.cshtml.cs

  3. Run program. I see my form.

  4. Click "submit". I get HTTP 400.

Pages\Index.cshtml.cs

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace HelloUploads.Pages
{
    public class IndexModel : PageModel
    { 
    
        public IActionResult OnGet()
        {
            return Page();
        }

        public IActionResult OnPost()
        {
            return RedirectToPage("./Index");
        }
    }
}

Index.cshtml

@page
@model HelloUploads.Pages.IndexModel
@{
    ViewData["Title"] = "Test";
}

<form method="post">
   <input type="submit" >
</form>

I'm sure the problem is simple. I've tried many variations, and I've been banging my head for several hours.

Q: What am I doing wrong? Any suggestions?


Solution

  • Your problem is probably anti-forgery tokens. Add @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers to the page

    @page
    @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
    @model HelloUploads.Pages.IndexModel
    @{
        ViewData["Title"] = "Test";
    }
    
    <form method="post">
       <input type="submit" >
    </form>
    

    on the code behind add [ValidateAntiForgeryToken] attribute

    [ValidateAntiForgeryToken]
    public IActionResult OnPost()
    {
       return RedirectToPage("./Index");
    }
    

    Hope it works!