Search code examples
c#asp.net-mvcasp.net-coreerror-handlingantiforgerytoken

Global Error Handling on AutoValidateAntiforgeryToken failure


I have this ASP.Net core web app. I've configured some custom error handlers in Startup.cs. Here you can see:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseWhen(context => context.Request.Path.StartsWithSegments("/api"), app =>
    {
        app.UseStatusCodePagesWithReExecute("/api/error-{0}");
    });

    app.UseWhen(context => !context.Request.Path.StartsWithSegments("/api"), app =>
    {
        app.UseStatusCodePagesWithRedirects("/error-{0}");
    });

    //...
}

Then there is a controller which has [AutoValidateAntiforgeryToken] above it.

The problem is that when AntiForgeryToken fails the valdation, request get responded with status code 400 and my custom error handler is not working. If I send the correct AntiForgeryToken or simply remove [AutoValidateAntiforgeryToken] attribute, then the custom error handler works just fine.

Is there a way to make [AutoValidateAntiforgeryToken] failure result to use the global error handler?


Solution

  • #SOLVED The problem occurres because the action of of custom error handler itself is inside the same controller; Thus the error handler action method itself required ant-forgery token! solved by adding [IgnoreAntiForgeryToken] above error handler action method.