Hem*_*rya 4 .net asp.net asp.net-core-mvc asp.net-core asp.net-core-1.1
我试图在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);
}
Run Code Online (Sandbox Code Playgroud)
起初我假设TempData默认工作,但后来意识到必须添加和配置它.我在启动时添加了ITempDataProvider.官方文件似乎描述了这应该足够了.它没用.然后我还将它配置为使用Session
public void ConfigureServices(IServiceCollection services)
{
services.AddMemoryCache();
services.AddSession(
options => options.IdleTimeout= TimeSpan.FromMinutes(30)
);
services.AddMvc();
services.AddSingleton<ITempDataProvider,CookieTempDataProvider>();
}
Run Code Online (Sandbox Code Playgroud)
在编写app.UseMvc之前,我的以下行与Startup的Configure方法中的Session相关.
app.UseSession();
Run Code Online (Sandbox Code Playgroud)
这仍然无效.发生的事情是我没有得到任何异常,因为我错过了一些配置之前我已经得到了TempData,但现在创建操作方法无法重定向到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);
}
Run Code Online (Sandbox Code Playgroud)
这是我们现在要做的额外工作,但看起来就像现在这样.
| 归档时间: |
|
| 查看次数: |
2407 次 |
| 最近记录: |