Unable to redirect action when using TempData in Core Asp.Net

I am trying to achieve a simple thing in Asp.Net Core. It wouldn't matter in Asp.Net Mvc. I have a way of doing things like this

public async Task<IActionResult> Create([Bind("Id,FirstName,LastName,Email,PhoneNo")] Customer customer)
    {
        if (ModelState.IsValid)
        {
            _context.Add(customer);
            await _context.SaveChangesAsync();
            TempData["CustomerDetails"] = customer;
            return RedirectToAction("Registered");
        }
        return View(customer);
    }

public IActionResult Registered()
    {
        Customer customer = (Customer)TempData["CustomerDetails"];
        return View(customer);
    }

      

At first I assumed TempData works by default, but later I realized that it should be added and configured. I added an ITempDataProvider on startup. The white paper seems to describe that this should be enough. It didn't work. Then I also configured it to use session

public void ConfigureServices(IServiceCollection services)
{
      services.AddMemoryCache();
      services.AddSession(
            options => options.IdleTimeout= TimeSpan.FromMinutes(30)
            );
      services.AddMvc();
      services.AddSingleton<ITempDataProvider,CookieTempDataProvider>();
}

      

I next line related to the "Session in Startup Setting" method before writing the .UseMvc application.

app.UseSession();

      

It doesn't work yet. What is happening is I am not getting any exceptions due to using TempData, which I got earlier when I missed some configuration, but now the action create method cannot redirect to the Registered method. The create method does all the work, but RedirectToAction has no effect. If I remove the line that assigns the Customer TempData details, RedirectToAction is successfully redirected to that action method. However, in this case, the registered action does not have access to the ClientDetails. What am I missing?

+4


source to share


1 answer


@Win. You were right. I realized that serialization, deserialization is required whenever you want to use TempData in Asp.net Core after reading the disclaimer in this article.

https://andrewlock.net/post-redirect-get-using-tempdata-in-asp-net-core/

I first tried using BinaryFormatter but found that it was also removed from .NET Core. Then I used NewtonSoft.Json for serialization and deserialization.



TempData["CustomerDetails"] = JsonConvert.SerializeObject(customer);

public IActionResult Registered()
    {
        Customer customer = JsonConvert.DeserializeObject<Customer>(TempData["CustomerDetails"].ToString());
        return View(customer);
    }

      

This is additional work that we have to do now, but it looks like it does now.

+5


source







All Articles