Search code examples
asp.netasp.net-coremodel-view-controllerrazor

How to error handle a Razor Page Form OnPost


I created a very basic Razor ASP.NET project and a test/experimental form that generates simple elements. It generates over a 1500 elements. On Form Post I have a public IActionResult OnPost method but it never gets there and just displays a "This page isn’t working right now" error even though I am in development. I know what the issue is and how to fix it, basically its "Form value count limit 1024"

What I want to know is how do I see any error on a IActionResult OnPost. I had to recreate this in a typical MVC project just to be able to see the error

    @page
    @model IndexModel
    @{
        ViewData["Title"] = "Home page";
    }
    
    @{
        var numberOfLines = 5000;
    }
    
    <form method="post" enctype="multipart/form-data" id="frmQuiz">
        <button type="submit" class="btn btn-secondary" asp-page-handler="Save" id="cmdSave">Complete</button>
    
        <!-- Your form fields go here -->
        @for (int i = 0; i < numberOfLines; i++)
        {
            <p></p><input type="text" id="exampleInput" name="exampleInput" value="QuestionAnswers[@(i + 1)].answers[1].answer.AnswerDesc">
        }
        <button type="submit" class="btn btn-secondary" asp-page-handler="Save" id="cmdSave">Complete</button>
    
        
    </form>
public class IndexModel : PageModel
{
    private readonly ILogger<IndexModel> _logger;

    public IndexModel(ILogger<IndexModel> logger)
    {
        _logger = logger;
    }

    public IActionResult OnPostSave()
    {
        //This method is not hit when there is more than 1024 form elements
        //How do I build error handling around a IActionResult OnPost method
        var request = Request.Form;


        return Page();
    }
}

enter image description here


Solution

  • Razor Pages are protected by Antiforgery validation by default. It will give you 400 error if you do not post with the antiforgery token. The post data may be cut without the token when they are out of size.

    You can disable CSRF antiforgery and then you can get into the handler to see the error.

    Disable CSRF antiforgery globally in Program.cs:

    builder.Services.AddRazorPages().AddRazorPagesOptions(o =>
    {
        o.Conventions.ConfigureFilter(new IgnoreAntiforgeryTokenAttribute());
    });
    

    Or disable by adding [IgnoreAntiforgeryToken] attribute in the razor pages you want:

    [IgnoreAntiforgeryToken]
    public class IndexModel : PageModel
    {
    }