asp.net-core-mvc - asp.net core 2.1 tempdata 为空,带有redirecttoaction
问题描述
我有一个 asp.net core 2.1 项目,我尝试将 TempData 与 RedirectToAction 一起使用,但它始终为空(没有错误)
这是我的 ConfigureServices 方法
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
//services pour l'authentification
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
{
options.LoginPath = "/Login";
});
//services pour session
services.AddSession(options => {
options.IdleTimeout = TimeSpan.FromMinutes(20);
});
//configuer port https
services.AddHttpsRedirection(options => options.HttpsPort = 443);
Dapper.DefaultTypeMap.MatchNamesWithUnderscores = true;
ManageDI(services);
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
.AddSessionStateTempDataProvider();
}
我有“app.UseSession();” 在我的配置方法中
这是我的代码
[HttpGet]
public async Task< IActionResult> ResetPassword(string query)
{
TempData["test"]= "test";
return RedirectToAction(nameof(Login));
}
[HttpGet]
public IActionResult Login(string returnUrl = null)
{
var b = TempData["test"];
//b is always null when calling ResetPassword action
var model = new Models.Account.LoginModel{
ReturnUrl = returnUrl
};
return View(model);
}
请问我忘记了什么?
谢谢
解决方案
根据您提供的代码,尚不完全清楚问题出在哪里,但是由于您在操作中提到它在您的ResetPassword
操作中为空Login
,因此我假设您没有正确地保留该值。
TempData
就是这样:临时数据。一旦被访问,它就会被删除。因此,当你b
在这里设置它的值时,就是这样——它消失了。如果您稍后尝试在另一个操作中访问它,或者甚至只是在此操作返回的视图中访问它,它现在将为 null。
如果您需要获取该值,但还要保留它以供以后使用,您需要使用TempData.Peek
:
var b = TempData.Peek("test");
推荐阅读
- command - 如何在 Ok Google 中创建带有自定义响应的自定义命令?
- browser - 在 Cypress 中,在测试前在 localStorage 中设置一个令牌
- numpy - Numpy - 在 3-d 矩阵中查找网格点的空间位置(知道该网格点的索引)
- ruby-on-rails - Rubocop Lint/Void:在 void 上下文中使用的文字
- php - 重定向包括 BLANK 或 /
- javascript - Jasmine 测试 sort() localecompare()
- jquery - 在jquery中计算keyup
- typescript - 收集装饰类(没有注册表类)
- python - Python:将电子邮件地址列表转换为发送电子邮件
- linux - 为什么 wget 更改文件类型?