Ber*_*ian 1 c# tempdata asp.net-core
您好,我正在尝试向其添加对象TempData并重定向到另一个控制器操作。使用时出现错误消息500 TempData。
public IActionResult Attach(long Id)
{
Story searchedStory=this.context.Stories.Find(Id);
if(searchedStory!=null)
{
TempData["tStory"]=searchedStory; //JsonConvert.SerializeObject(searchedStory) gets no error and passes
return RedirectToAction("Index","Location");
}
return View("Index");
}
public IActionResult Index(object _story)
{
Story story=TempData["tStory"] as Story;
if(story !=null)
{
List<Location> Locations = this.context.Locations.ToList();
ViewBag._story =JsonConvert.SerializeObject(story);
ViewBag.rstory=story;
return View(context.Locations);
}
return RedirectToAction("Index","Story");
}
Run Code Online (Sandbox Code Playgroud)
PS阅读可能的解决方案我已添加 app.UseSession()到Configure方法services.AddServices()中,ConfigureServices但方法无济于事。是否有任何我必须注意的模糊设置?
PS添加ConfigureServices和UseSession
配置服务
public void ConfigureServices(IServiceCollection services)
{
services.AddOptions();
services.AddDbContext<TreasureContext>(x=>x.UseMySql(connectionString:Constrings[3]));
services.AddMvc();
services.AddSession();
}
Run Code Online (Sandbox Code Playgroud)
配置
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseSession();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
Run Code Online (Sandbox Code Playgroud)
您必须先序列化对象,然后再将其分配给TempData,因为核心仅支持字符串而不支持复杂的对象。
TempData["UserData"] = JsonConvert.SerializeObject(searchedStory);
Run Code Online (Sandbox Code Playgroud)
并通过反序列化检索对象。
var story = JsonConvert.DeserializeObject<Story>(TempData["searchedStory"].ToString())
Run Code Online (Sandbox Code Playgroud)
您services.AddMemoryCache();的 ConfigureServices() 方法中缺少 一行。像这样:
services.AddMemoryCache();
services.AddSession();
services.AddMvc();
Run Code Online (Sandbox Code Playgroud)
之后 TempData 应该按预期工作。
| 归档时间: |
|
| 查看次数: |
2445 次 |
| 最近记录: |