你好,我正在尝试将对象添加到 TempData
并重定向到另一个 Controller 操作。我在使用 TempData
时收到错误消息 500。
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");
}
P.S 通读可能的解决方案,我已将 app.UseSession()
添加到 Configure
方法,并将 services.AddServices()
添加到 ConfigureServices
方法但无济于事。是否有任何我必须注意的晦涩设置?
P.S 添加 ConfigureServices
和 UseSession
配置服务
public void ConfigureServices(IServiceCollection services)
{
services.AddOptions();
services.AddDbContext<TreasureContext>(x=>x.UseMySql(connectionString:Constrings[3]));
services.AddMvc();
services.AddSession();
}
配置
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?}");
});
}
最佳答案
您必须在将对象分配给 TempData 之前对其进行序列化,因为核心仅支持字符串而不支持复杂对象。
TempData["UserData"] = JsonConvert.SerializeObject(searchedStory);
并通过反序列化来检索对象。
var story = JsonConvert.DeserializeObject<Story>(TempData["searchedStory"].ToString())
关于c# - 在 .NET Core MVC 应用程序中使用 TempData 时出现错误 500,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48409313/