4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ASP.NET MVC TempDataはアクセスしても消えないことがある

Posted at

ASP.NET MVC
.NET 4.7.2
C#

SessionのスマートラッパーらしいTempData
…一度値をgetすると削除マークされて現在のリクエストが終了するときに存在が削除される。
という、ちょっと便利なやつ程度の認識でした。

削除マークを付けないように(削除マークを消すのも)

TempData.Keep()      TempData
TempData.Keep(KEY)   指定のTempData

を現在のリクエスト内で明示的に呼ぶいう。

で、Keep()していないのに?
次のリクエストでもバッチリ居座っている現象が発生。
特定のActionMethodで毎回getで前回と同じ値が取得できてしまう。

結論。
RedirectはKeepしてますね。

RedirectToAction()
Redirect()

スグに試せた対策

TempData.Remove(string key)

スグに消しておく。


いやいや、どっかで再セットしてるだろ → ない
ActionMetho内でgetしているタイミングを変えてみる → 消えない
直前の別ActionMethodでTempDataをgetしてみる → 消える

Keep()していないのに?

どっかでKeep()してないかの視点に立つ。
プログラミングMicrosoft ASP.NET MVC 第3版によると。

データがメモリ内にとどまるのは、現在のリクエストと次のリダイレクトという2つのリクエストの間だけです。

んー。

        public ActionResult Index()
        {
            TempData[TempDataKey] = "TempValue";
            return View();
        }

        public ActionResult About()
        {
            var result = getTempData(MethodBase.GetCurrentMethod().Name)
            System.Diagnostics.Debug.WriteLine(result);

            return RedirectToAction("Contact");
            // return Redirect("Contact"); // 同じ
        }

        public ActionResult Contact()
        {
            var result = getTempData(MethodBase.GetCurrentMethod().Name)
            System.Diagnostics.Debug.WriteLine(result);

            return View();
        }

Index → About →(Redirect)→ Contact

About Get!:TempValue
Contact Get!:TempValue

ContactでTempData取れてるじゃん。

About → Contact

About Empty!
Contact Empty!

TempData消滅。

        const string TempDataKey = "TEMP_KEY";

        private string getTempData(string actionMethodName)
        {
            var tempData = TempData[TempDataKey];
            if (tempData != null)
            {
                return ($"{actionMethodName} Get!:{tempData.ToString()}");
            }
            else
            {
                return ($"{actionMethodName} Empty!");
            }
        }

これって当たり前のなのか… どっかにReferenceとかないのかな。
参考文献 プログラミングMicrosoft ASP.NET MVC 第3版 日経BP社 P.273
4
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?