在.NET Core MVC应用程序中使用TempData时出现错误500

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添加ConfigureServicesUseSession

配置服务

 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)

Agr*_*dha 7

您必须先序列化对象,然后再将其分配给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)

  • 这是我的问题,这让我发疯。使用复杂对象导致我返回500错误,没有任何异常或对它返回500的任何解释。序列化是解决之道。 (3认同)

fat*_*ine 5

services.AddMemoryCache();的 ConfigureServices() 方法中缺少 一行。像这样:

        services.AddMemoryCache();
        services.AddSession();
        services.AddMvc();
Run Code Online (Sandbox Code Playgroud)

之后 TempData 应该按预期工作。

  • *Asp.net Core 3 用户注意事项* 此解决方案不适用于您,请参阅 Agrawal Shraddha 解决方案。 (3认同)