Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?}");
            });
        }
like image 223
Bercovici Adrian Avatar asked Jan 23 '18 19:01

Bercovici Adrian


2 Answers

You have to serialize the object before assigning it to TempData as core only support strings and not complex objects.

TempData["UserData"] = JsonConvert.SerializeObject(searchedStory);

and retrieve the object by deserializing it.

var story = JsonConvert.DeserializeObject<Story>(TempData["searchedStory"].ToString())
like image 125
Agrawal Shraddha Avatar answered Oct 18 '22 16:10

Agrawal Shraddha


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.

like image 25
fatherOfWine Avatar answered Oct 18 '22 15:10

fatherOfWine