简体   繁体   中英

RedirectToAction is not working with Tempdata - ASP.net core MVC

I have this method in which I am trying to redirect the request to a different controller. To the called controller , I need some data from the previous controller and so I had this put in the Tempdata. But when I use Tempdata before the line where I call RedirectToAction, the requested is not getting passed to the next action at all

Like in the below code

public IActionResult GetAuthToken()
        {
            //Logic to generate AuthToken 

            //TODO:SRI 14/03/2017 Get the UserId from the front end app, For now I am hardcoding this value

            AccountHolderDetails user = new AccountHolderDetails
            {
                UserId = "123",
                FirstName = "",
                LastName = "",
                Email = "",
                Phone = "",
                Address = new UserAddress
                {
                    Street = "123 anystreet",
                    City = "Brantford",
                    State = "ON",
                    Country = "CA"//,
                                  //PostalCode = "M4P1E8"
                }
            };

            var uniqueId = Guid.NewGuid();
            var authToken = GenerateAuthToken(user.UserId, uniqueId);
            var transactionRecord = CreateTransactionRecord(user,uniqueId,authToken);

            // HttpContext.Session.Set("UserData", user);

            TempData["UserData"] = user;
            TempData["TransactionData"] = transactionRecord;

            return RedirectToAction("Authorize", "Authorization");

        }

I am setting the Tempdata just before calling redirecttoaction, and when the code executes it is not going to the Authorization controller to thw authorize method.

I tried commenting the tempdata part of the lines in above code and it is working fine,but I need the user data in the authorization controller and hence using tempdata. I have followed instructions from the core website to configure sessions and all of that is fine like below check out my starttup.cs class

public void ConfigureServices(IServiceCollection services)
        {
            services.AddDistributedMemoryCache();
            services.AddSession(options => {
                options.IdleTimeout = TimeSpan.FromSeconds(10);
                options.CookieHttpOnly = true;

            });

            // Add framework services.
            services.AddMvc();

            services.Configure<WireCardSettings>(Configuration);

            services.AddSingleton<ITempDataProvider, CookieTempDataProvider>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseSession();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }

You have to serialize the object before assigning it to TempData.

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

and retrieve the object by deserializing it.

var user = JsonConvert.DeserializeObject<AccountHolderDetails>(TempData["UserData"].ToString());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM