TempData 不适用于 MVC4 中的第二个请求

syd*_*yos 5 asp.net-mvc-4

我以前从未见过这个并且被难住了。我有以下控制器序列:

    /// <summary>
    /// Helper method to store offerId to TempData
    /// </summary>
    /// <param name="offerId"></param>
    private void StoreOfferInTempData(string offerId)
    {
        if (TempData.ContainsKey(SelectedOfferKey))
            TempData.Remove(SelectedOfferKey);
        TempData.Add(SelectedOfferKey, offerId);
    }

    [HttpPost]
    [AllowAnonymous]
    public virtual ActionResult Step1(MyViewModel model)
    {
        if (ModelState.IsValid)
        {
            StoreOfferInTempData(model.SelectedOfferId);
            return RedirectToAction(MVC.Subscription.Register());
        }

        MySecondViewModel model2 = new MySecondViewModel { OfferId = model.SelectedOfferId };
        return View(model2);
    }


    [HttpGet]
    [AllowAnonymous]
    public virtual ActionResult Register()
    {
        string offerId = TempData[SelectedOfferKey] as string; //we get a valid value here
        ... error handling content elided ...

        RegisterViewModel model = new RegisterViewModel { OfferId = offerId };

        return View(model);
    }

    [HttpPost]
    [AllowAnonymous]
    public virtual ActionResult Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            CreateCustomerResult result = CustomerService.CreateAccount(model.Email, model.NewPassword);
            if (result.Success)
            {
                ... content elided; storing customer to Session ...                    
                MyMembershipProvider.PersistUserCookie(result.Principal, true);

                //need to store our selected OfferId again for use by the next step
                StoreOfferInTempData(model.OfferId);
                return RedirectToAction(MVC.Subscription.Payment());
            }

            model.ErrorMessage = result.ErrorMessage;
        }

        return View(model);
    }


    [HttpGet]
    public ActionResult Payment()
    {
        string offerId = TempData[SelectedOfferKey] as string; //this is null???

        ... content elided ...

        return View(model);
    }
Run Code Online (Sandbox Code Playgroud)

TempData 的第一轮存储行为符合预期。该值出现在后续的 HttpGet 方法中,并被标记为删除,以便当我再次添加它时它不再存在。但是,在第三个 HttpGet 方法上,它返回 null。

我尝试过在每一轮中使用不同的密钥,但没有任何变化。我可以向您保证,除了显示的值之外,我不会检查 TempData,因此我认为该值不会以某种方式被标记为删除。此外,无论是否具有 [AllowAnonymous] 属性,它都会在付款方法中失败(因此不是由于任何 http 到 https 切换或类似的原因。

看起来这一定是非常简单的事情,但我的搜索却一无所获。非常感谢任何帮助。

更新:经过进一步检查,出于某种原因,我的整个上下文似乎都集中在这一步上。我们在控制器中使用 IoC,但没有 IoC 实例化的项目。谜团加深了。

syd*_*yos 1

啊哈!好吧,这太晦涩了,我希望它对其他人有帮助。事实证明,我忘记在创建 Payment() 操作后运行 T4MVC.tt 文件,因此采用 MVC.Subscription.Payment() 操作的 RedirectToAction 未正确实例化控制器。我不清楚这里所有的底层魔法,但如果您遇到这个问题并且正在使用 T4MVC.tt,请确保您运行了它!

欢迎评论为什么会这样。