TempData返回空

时间:2019-10-23 12:18:11

标签: asp.net-core asp.net-core-mvc

我正在初始化Tempdata 我需要在另一个操作中检索tempdata,但它返回null。

    public  IActionResult GetRestaurants(int? id)
    {
        TempData["HotelID"] = id;

        return Ok();
    }
    [HttpPost]
    public IActionResult AddRestaurant()
    {

      int x =int.Parse(TempData["HotelID"].ToString());

    }

1 个答案:

答案 0 :(得分:1)

startup.cs的ConfigureServices方法:

public void ConfigureServices(IServiceCollection services)
        {
            services.AddMemoryCache();
            services.AddSession();
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

配置startup.cs的方法

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

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

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();
        }

更多详细信息,请访问Session and app state in ASP.NET Core

Index1操作方法

 public IActionResult Index()
            {
                Message = $"Customer abcd added";
                TempData["name"] = "Test data";
                TempData["age"] = 30;
                TempData.Keep();


               // Session["name"] = "Test Data";

                return View();
            }

index2操作方法

 public IActionResult About()
        {

           var userName = TempData.Peek("name").ToString();


           var userAge = int.Parse(TempData.Peek("age").ToString());
            return View();
        }