【问题标题】:asp.net core 2.1 tempdata empty with redirecttoactionasp.net core 2.1 tempdata 为空,带重定向操作
【发布时间】:2018-10-16 15:55:48
【问题描述】:

我有一个 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-mvc asp.net-core-2.1


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-04
    • 1970-01-01
    • 2021-10-06
    相关资源
    最近更新 更多