Bagzli
Bagzli

Reputation: 6579

How to show custom page for 400 error in .net core 3.0

I have my error handling setup in the following way:

Startup.cs

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseMiddleware<ExceptionHandlerMiddleware>();
    app.UseStatusCodePagesWithReExecute("/Error/Index");

    //I Added this as a test but it had no effect.
    app.Use((context, next) => {
        context.SetEndpoint(null);
        return next();
    });
    app.UseStaticFiles(new StaticFileOptions()
    {
        OnPrepareResponse = (context) =>
        {
            context.Context.Response.GetTypedHeaders()
                .CacheControl = new CacheControlHeaderValue
            {
                MaxAge = TimeSpan.FromDays(30)
            };
        }
    });

    app.UseRouting();
    app.UseAuthentication();
    app.UseAuthorization();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });
}

Now I tested this by trying something like localhost/mynotexistantpage and it works, I get my error page. Actually in most scenarios when I have tested this I got the error page. But there is one scenario where I don't get that page.

If you create a post action (any action really) and require a antiforgery token on it. Now if you submit a form to that method but in your html remove the antiforgery token that is automatically generated, the server responds with a 400 status and my error page is not used. The page that I get is one that the browser defaults to if you don't serve one.

An additional note: my exception handler did not even catch this error. The handler constructor looks something like this:

public async Task Invoke(HttpContext context)
{
    try
    {
        await _requestDelegate.Invoke(context);
    }
    catch (Exception exception)
    {
        HandleExceptionAsync(context, exception);
    }
}

Why is this and how can I account for all scenarios when it comes to error handling?

Upvotes: 1

Views: 1435

Answers (2)

Bagzli
Bagzli

Reputation: 6579

This was actually 2 problems. The first problem is a bug and a workaround can be found here:

https://github.com/aspnet/AspNetCore/issues/13715#issuecomment-528929683

The second problem was because I have auto validation on anti forgery token. This means that when page re-executes it is a post again and thus the anti-forgery fails again thus not being able to reach my error page. So the solution to that was to add IgnoreAntiforgeryToken attribute on the error controller.

Upvotes: 2

Muhammad Hannan
Muhammad Hannan

Reputation: 2567

When antiforgery validation fails server (ASP.Net Core) returns error 404 and stops further processing of the request and none of your exception handlers will catch that error. What you can do is use UseStatusCodePagesWithRedirects like below

app.UseStatusCodePagesWithReExecute("/Error"); // "/Error" is your custom error handling page.

And then do whatever you like to do with errors.

A full sample app here for error handling using UseStatusCodePagesWithReExecute.

Upvotes: 0

Related Questions