AlDev
AlDev

Reputation: 173

How can I intercept and handle an AntiForgeryToken exception?

I am using jQuery to post($.post) to a controller action and return a JSON result.

If there are any errors, I'm returning the error message with the JSON result and displaying it to the user with a modal.

However, I'm having a lot of trouble intercepting the AFT exception.

Rather than throw a 500, I just want to grab the error message and send the result back to the user.

... and, if I simply try to handle the error, I can't figure out how to stop it from canceling execution of the action method

Upvotes: 0

Views: 1340

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038790

You could trap this error in Application_Error and if the request was asynchronous send the proper JSON in the response containing the error message.

Upvotes: 1

user1151
user1151

Reputation:

A token error is not meant to be handled by your code - it's a filter directive that happens before the Action is actually executed (a valid token is required before execution - this is for security).

You could probably get around this by creating your own ActionFilter - but this is Trouble (with a capital T) - I might suggest you find another way of doing it or let it fail. You could also do a test for a return value in your script - if nothing comes in you could show a message.

Upvotes: 1

Related Questions