ASP.NET TempData isn't cleared even after reading it

偶尔善良 提交于 2019-12-10 14:18:19

问题


I have a controller action something similar to the below, TempData was initialized by my framework. I've noticed that TempData doesn't clear out the value once it is read as shown in the action "EmployeeUnderAge".

When does TempData clears the data that has been read?

public class HomeController : Controller
{
    public ActionResult Index(int iD)
    {
        var employeeAge = (int)TempData["Age"];
        RouteData.Values.Add("Age", employeeAge);
        return RedirectToAction("EmployeeUnderAge");
    }

    public ActionResult EmployeeUnderAge(int employeeAge)
    {
        var stillInTempData = (employeeAge == ((int) TempData["Age"]));
        return (stillInTempData) ? View("Index") : View("Error");
    }
}

回答1:


Below are some of the key points to note when using Temp data.

  1. A read access to temp data doesn't remove items from the dictionary immediately, but only marks for deletion.

  2. TempData will not always remove the item that has been read. It only removes the item when an action results in an HTTP 200 (OK) status code (ie: ViewResult/JsonResult/ContentResult etc)

  3. In case of actions that result in an HTTP 302 (such as any redirect actions), the data is retained in storage even when it is accessed which is the case in my question. TempData apparently is designed for passing data to different controllers/actions and hence doesn't clearing out during redirects is justified



来源:https://stackoverflow.com/questions/32571599/asp-net-tempdata-isnt-cleared-even-after-reading-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!