如何拦截并处理 AntiForgeryToken 异常?
我正在使用 jQuery 将 post($.post) 发送到控制器操作并返回 JSON 结果。
如果出现任何错误,我将返回带有 JSON 结果的错误消息,并使用模式将其显示给用户。
但是,我在拦截 AFT 异常时遇到了很多麻烦。
我不想抛出 500,而是想获取错误消息并将结果发送回用户。
...并且,如果我只是尝试处理错误,我无法弄清楚如何阻止它取消操作方法的执行
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
令牌错误并不意味着由您的代码处理 - 它是在实际执行操作之前发生的过滤器指令(执行之前需要有效的令牌 - 这是为了安全起见)。
您可能可以通过创建自己的 ActionFilter 来解决这个问题 - 但这是麻烦(大写 T) - 我可能建议您找到另一种方法来做到这一点,或者让它失败。您还可以对脚本中的返回值进行测试 - 如果没有任何内容,您可以显示一条消息。
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.
您可以在
Application_Error
中捕获此错误,如果请求是异步的,则在包含错误消息的响应中发送正确的 JSON。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.