首页 > 解决方案 > asp.net core 2.1 tempdata 为空,带有redirecttoaction

问题描述

我有一个 asp.net core 2.1 项目,我尝试将 TempData 与 RedirectToAction 一起使用,但它始终为空(没有错误)

这是我的 ConfigureServices 方法

public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        //services pour l'authentification
        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
        {
            options.LoginPath = "/Login";
        });


        //services pour session
        services.AddSession(options => {
            options.IdleTimeout = TimeSpan.FromMinutes(20);
        });

        //configuer port https
        services.AddHttpsRedirection(options => options.HttpsPort = 443);

        Dapper.DefaultTypeMap.MatchNamesWithUnderscores = true;

        ManageDI(services);

        services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
            .AddSessionStateTempDataProvider();
    }

我有“app.UseSession();” 在我的配置方法中

这是我的代码

[HttpGet]
    public async Task< IActionResult> ResetPassword(string query)
    {
        TempData["test"]= "test";
        return RedirectToAction(nameof(Login));
    }

    [HttpGet]
    public IActionResult Login(string returnUrl = null)
    {
        var b = TempData["test"];
        //b is always null when calling ResetPassword action

        var model = new Models.Account.LoginModel{
                ReturnUrl = returnUrl
        };

        return View(model);
    }

请问我忘记了什么?

谢谢

标签: asp.net-core-mvcasp.net-core-2.1

解决方案


根据您提供的代码,尚不完全清楚问题出在哪里,但是由于您在操作中提到它在您的ResetPassword操作中为空Login,因此我假设您没有正确地保留该值。

TempData就是这样:临时数据。一旦被访问,它就会被删除。因此,当你b在这里设置它的值时,就是这样——它消失了。如果您稍后尝试在另一个操作中访问它,或者甚至只是在此操作返回的视图中访问它,它现在将为 null。

如果您需要获取该值,但还要保留它以供以后使用,您需要使用TempData.Peek

var b = TempData.Peek("test");

推荐阅读