ASP.NET 核心 2.1:在 HTTP POST 验证失败后导航回页面显示浏览器错误

ASP.NET Core 2.1: Navigating back to a page after an HTTP POST fails validation displays a browser error

问题:

使用 ASP.NET Core 2.1 MVC 项目,使用浏览器后退按钮 return 后,我收到以下浏览器错误消息表单,其中表单 POST 服务器端验证失败:

Firefox 中的错误消息:

Document Expired

This document is no longer available.

The requested document is not available in Firefox’s cache.

  • As a security precaution, Firefox does not automatically re-request sensitive documents.
  • Click Try Again to re-request the document from the website.

Chrome 中的错误消息:

Confirm Form Resubmission

This webpage requires data that you entered earlier in order to be properly displayed. You can send this data again, but by doing so you will repeat any action this page previously performed.

Press the reload button to resubmit the data needed to load the page.

ERR_CACHE_MISS

重现步骤:

  1. 提交 HTML 表单 post,其中服务器端验证失败
  2. 导航到另一个 URL
  3. 单击浏览器后退按钮 return 到带有表单的页面

备注:

这似乎与禁用防伪系统的响应缓存 (https://docs.microsoft.com/en-us/aspnet/core/performance/caching/middleware?view=aspnetcore-2.1) 有关。

The Antiforgery system for generating secure tokens to prevent Cross-Site Request Forgery (CSRF) attacks sets the Cache-Control and Pragma headers to no-cache so that responses aren't cached. For information on how to disable antiforgery tokens for HTML form elements, see ASP.NET Core antiforgery configuration.

我可以确认,如果您从 HTML 表单中删除 @Html.AntiForgeryToken(),浏览器错误消息就会消失。

使用 AntiForgeryToken.

ASP.NET MVC5 中这不是问题

问题:

ASP.NET Core 2.1中,有没有人找到继续使用Antiforgery系统并防止在浏览器后退按钮时显示此浏览器错误消息的方法被使用了?

这是我的 POST 操作:

    [HttpPost]
    [ValidateAntiForgeryToken]
    [ActionName("Contact-Form")]
    public async Task<ActionResult> ContactForm(ContactFormViewModel cfvm)
    {
        if (ModelState.IsValid)
        {
            // << Handling of the form submit code here >>

            TempData["Success"] = string.Format("Your contact request was submitted successfully!");

            return RedirectToAction("Contact-Form-Success");
        }

        TempData["Error"] = "The form did not submit successfully. Please verify that all of the required fields are filled.";
        return View();
    }

更新:

我 post 在 ASP.NET 核心文档上编辑了这个问题: https://github.com/aspnet/Docs/issues/7590

这不是特定于语言的问题。这是一种浏览器行为。说这是 'not an issue with ASP.NET MVC 5' 是不正确的。

解决方案: 解决此问题的常用方法是自 1995 年以来一直存在的 PRG pattern

可以找到 ASP.NET 核心的此实现,使用 TempData here

而且我认为这个 link 对您最有帮助,因为它演示了在 MVC 5 和 MVC 6 中实现的方法。

希望对您有所帮助!

如果时间允许,我将尝试使用基于剃刀页面入门项目的示例尽快更新此 post。