.net core Razor Page TempData不工作,RedirectToPage后无法获取值怎么办?

发布时间 2023-12-01 22:42:35作者: jopny

问题:

.net core旧项目更新到.net core 8.0后,发现之前的错误反馈信息显示不出来了,经过反复搜索,询问人工智能无果。

之前怀疑/测试过:

1. 新版浏览器chrome访问https://localhost是否限制了Cookie

2. 浏览器是否受欧盟Cookie法规的要求进行了限制。

3. 写法错误

Razor page TempData的用法测试示例:参考这里:

TempData In Razor Pages , 19/06/2023 08:33:34,当初学习就是看的这篇文章,过了这么多年,这老兄竟然还更新了这篇文章,实在是佩服。

我自己的项目TempData是通过Cookie传输的,查看打开的网站,是有Cookie保存的,登录状态的Cookie都是正常的。但就是TempData不工作。

真正原因:

Program.cs中Cookie设置默认是只启用了必须的部分(比如记录访问者唯一ID,登录状态),TempData不是必须的(essential), 所以TempData不会被记录。

解决办法:

将以下代码添加到Program.cs中,即可解决问题。

services.Configure<CookieTempDataProviderOptions>(options => {
   options.Cookie.IsEssential = true;

搜到的原文附到这里:

Nothing's wrong with middleware order as described on official docs, which is:

  1. Exception/error handling
  2. HTTP Strict Transport Security Protocol
  3. HTTPS redirection
  4. Static file server
  5. Cookie policy enforcement
  6. Authentication
  7. Session
  8. MVC

But when we use Cookie policy enforcement (UseCookiePolicy), only essential cookie that will be sent to the browser and Cookie from Tempdata provider is not essential hence the problem. So we have to make it essential according to official documentation:

The Tempdata provider cookie isn't essential. If tracking is disabled, the Tempdata provider isn't functional. To enable the Tempdata provider when tracking is disabled, mark the TempData cookie as essential in Startup.ConfigureServices

// The Tempdata provider cookie is not essential. Make it essential
// so Tempdata is functional when tracking is disabled.
services.Configure<CookieTempDataProviderOptions>(options => {
   options.Cookie.IsEssential = true;
});

Adding those lines should solve your issue without reordering middleware.