我正在尝试在Asp.Net Core中实现一个简单的事情。在Asp.Net Mvc中,这没什么大不了的。我有一个这样的动作方法
public async Task<IActionResult> Create([Bind("Id,FirstName,LastName,Email,PhoneNo")] Customer customer)
{
if (ModelState.IsValid)
{
_context.Add(customer);
await _context.SaveChangesAsync();
TempData["CustomerDetails"] = customer;
return RedirectToAction("Registered");
}
return View(customer);
}
public IActionResult Registered()
{
Customer customer = (Customer)TempData["CustomerDetails"];
return View(customer);
}
起初,我假设TempData默认工作,但后来意识到必须添加和配置它。我在启动时添加了ITempDataProvider。官方文件似乎描述这应该足够了。没用 然后我还配置了它以使用会话
public void ConfigureServices(IServiceCollection services)
{
services.AddMemoryCache();
services.AddSession(
options => options.IdleTimeout= TimeSpan.FromMinutes(30)
);
services.AddMvc();
services.AddSingleton<ITempDataProvider,CookieTempDataProvider>();
}
我在编写app.UseMvc之前,在Startup的Configure方法中与Session相关的以下行。
app.UseSession();
这仍然无法正常工作。发生的事情是,由于不再使用TempData,我没有遇到任何异常,这是我之前错过某些配置时得到的,但是现在create action方法无法重定向到Registered Method。Create方法可以完成所有工作,但RedirectToAction无效。如果我删除了将客户详细信息分配给TempData的行,则RedirectToAction将成功重定向到该操作方法。但是,在这种情况下,注册操作方法显然无法访问CustomerDetails。我想念什么?
@赢得。你是对的。阅读本文中的免责声明后,我意识到只要想在Asp.net Core中使用TempData,就必须进行序列化和反序列化。
https://andrewlock.net/post-redirect-get-using-tempdata-in-asp-net-core/
我首先尝试使用BinaryFormatter,但发现它也已从.NET Core中删除。然后,我使用NewtonSoft.Json进行序列化和反序列化。
TempData["CustomerDetails"] = JsonConvert.SerializeObject(customer);
public IActionResult Registered()
{
Customer customer = JsonConvert.DeserializeObject<Customer>(TempData["CustomerDetails"].ToString());
return View(customer);
}
那是我们现在要做的额外工作,但看起来现在是这样。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句