Search code examples
c#asp.net-coretempdata

Error 500 when using TempData in .NET Core MVC application


Hello i am trying to add an object to TempData and redirect to another controller-action. I get error message 500 when using 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");
}

P.S Reading through possible solutions I have added app.UseSession() to the Configure method and services.AddServices() in the ConfigureServices method but to no avail.Are there any obscure settings i must be aware of?

P.S adding ConfigureServices and UseSession

ConfigureServices

 public void ConfigureServices(IServiceCollection services)
            {
                services.AddOptions();
                services.AddDbContext<TreasureContext>(x=>x.UseMySql(connectionString:Constrings[3]));
                services.AddMvc();
                services.AddSession();
            }

Configure

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?}");
            });
        }

Solution

  • You are missing services.AddMemoryCache(); line in your ConfigureServices() method. Like this:

            services.AddMemoryCache();
            services.AddSession();
            services.AddMvc();
    

    And after that TempData should be working as expected.