在我的索引中,我添加了一个搜索字段。
当用户输入搜索词并单击过滤器时,索引(Index)将被过滤。 到目前为止,一切都很好。
我想要实现的是,如果用户在同一 Controller 中执行其他操作(编辑、详细信息、删除等)并返回到索引,我希望恢复搜索。
为此,我使用了 TempData
但没有成功。
在各种论坛/教程中,我发现关于生命周期的冲突。 有人说:
lifetime of an object placed in TempData is exactly one additional request.
在另一个网站上我发现:
Data stored in TempData will be alive in the cookie until you read it from the TempData dictionary.
查看此article
那么真相在哪里: 只有一个子请求或当我读取 TempData 时?
我的测试说第二个:“直到您阅读它”(或过期时)
这是我的启动代码
public void ConfigureServices(IServiceCollection services)
{
// [..]
// Relevant code only
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
// Set a short timeout for easy testing.
options.IdleTimeout = TimeSpan.FromMinutes(15);
options.CookieHttpOnly = true;
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
// [..]
// Relevant code only
app.UseSession();
}
在我的 Controller 上
public async Task<IActionResult> Index(int page, string search)
{
search = search ?? TempData["Search"]?.ToString();
// Query with search data
TempData["search"] = search;
}
如果我在此 Controller 上搜索,TempData 会保存搜索词。
如果在列表中搜索后,我导航到其他页面然后返回此处,则搜索词仍然存在
我已经知道存在 .Keep
、.Peek
和其他管理 TempData
的方法
问题
- 如何管理操作之间的搜索词?
- 临时数据如何工作(直到重新读取或出现一个令人上瘾的请求)?
最佳答案
从许多旧的 Stack Overflow 帖子和文章来看,在早期版本的 ASP.NET 中,TempData
似乎只持续到下一个请求。然而,根据 Microsoft 的说法,.NET Core 的情况并非如此:
ASP.NET Core exposes the Razor Pages
TempData
or ControllerTempData
. This property stores data until it's read in another request. TheKeep(String)
andPeek(string)
methods can be used to examine the data without deletion at the end of the request.Keep
marks all items in the dictionary for retention.
我反复看到的关于 TempData
的另一个说法是它是如何使用 session 实现的,但这不是 .NET Core 的默认机制:
The cookie-based
TempData
provider is enabled by default. To enable the session-basedTempData
provider, use theAddSessionStateTempDataProvider
extension method.
来源: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-3.1#tempdata
关于Asp.net Core TempData 生命周期和搜索词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44417547/