In-depth analysis of the load and save operations of ASP. net mvc 1.0-2. Controller. Execute (request)-tempdatadictionary

Source: Internet
Author: User

Controller finally creates and executes an action by calling the execute (requestcontext) method of the controllerbase class. The Code is as follows:

protected virtual void Execute(RequestContext requestContext) {            if (requestContext == null) {                throw new ArgumentNullException("requestContext");            }            Initialize(requestContext);            ExecuteCore();        }

The code is divided into two steps:

  • Initialize (requestcontext ):Creates an instance of the controllercontext class.
  • Executecore ():Load tempdata, create and execute actions, process the actionresult returned by the action, and save tempdata.

The executecore () code is as follows:

protected override void ExecuteCore() {            TempData.Load(ControllerContext, TempDataProvider);            try {                string actionName = RouteData.GetRequiredString("action");                if (!ActionInvoker.InvokeAction(ControllerContext, actionName)) {                    HandleUnknownAction(actionName);                }            }            finally {                TempData.Save(ControllerContext, TempDataProvider);            }        }

The code is divided into three parts:

  1. Tempdata. Load (controllercontext, tempdataprovider ):Load tempdata from httpcontextbase. Session
  2. Actioninvoker. invokeaction (controllercontext, actionname ):Create, execute the action, and process the actionresult returned by the action
  3. Tempdata. Save (controllercontext, tempdataprovider ):Save tempdata

1st and 3rd are all operations on tempdata. The following sections describe these two steps in detail.

 

1. tempdata. Load (controllercontext, tempdataprovider)

Tempdataprovider: sessionstatetempdataprovider. It is a session helper class that inherits the itempdataprovider interface.

Source code of tempdataprovider. Load:

public void Load(ControllerContext controllerContext, ITempDataProvider tempDataProvider) {            IDictionary<string, object> providerDictionary = tempDataProvider.LoadTempData(controllerContext);            _data = (providerDictionary != null) ? new Dictionary<string, object>(providerDictionary, StringComparer.OrdinalIgnoreCase) :                 new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);            _initialKeys = new HashSet<string>(_data.Keys);            _modifiedKeys.Clear();        }

Here is the whole process of loading tempdata:

  1. Call loadtempdata (…) In sessionstatetempdataprovider (...) Method and returns an idictionary <string, Object> object.
  2. Initialize the _ data object. If providerdictionary is not null, store the data in providerdictionary to the _ data object. In fact, this _ data is the container that tempdata uses to save data,
  3. Initialize the _ initialkeys object and put all the key values in _ data into it. It is used to cache the loaded key values. If you insert new data to tempdata, _ The data in the initialkeys object does not change tasks.
  4. Clears the value in _ modifiedkeys to save the new key value of tempdata. When a new key-value pair is inserted into tempdata, the key value is saved to the _ modifiedkeys object.

Let's dive into the tempdataprovider. loadtempdata (controllercontext) method, which is actually the loadtempdata (…) In the sessionstatetempdataprovider class (...) Method:

public virtual IDictionary<string, object> LoadTempData(ControllerContext controllerContext) {            HttpContextBase httpContext = controllerContext.HttpContext;                        if (httpContext.Session == null) {                throw new InvalidOperationException(MvcResources.SessionStateTempDataProvider_SessionStateDisabled);            }            Dictionary<string, object> tempDataDictionary = httpContext.Session[TempDataSessionStateKey] as Dictionary<string, object>;            if (tempDataDictionary != null) {                // If we got it from Session, remove it so that no other request gets it                httpContext.Session.Remove(TempDataSessionStateKey);                return tempDataDictionary;            }            else {                return new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);            }        }

The sessionstatetempdataprovider class defines a constant and uses it as the key of the tempdata object stored in the session.

internal const string TempDataSessionStateKey = "__ControllerTempData";

In loadtempdata (...) Method, first look for the dictionary <string, Object> object corresponding to the key in the session. If this object exists in the session, clear the key-value pair in the session and return the found dictionary <string, Object> object. Otherwise, create a new dictionary <string, Object> object and return it.

The focus here isHttpcontext. session. Remove (tempdatasessionstatekey)Method, which is also tempdataFeaturesThat is, the same tempdata can only be passed once. After tempdata is found in the session, it is immediately removed from the session. The next time loadtempdata (…) is executed (...) Method will never find the same tempdata.

Note again:You only need to put a key-value pair into tempdata. Either different actions in the same controller or different actions in different controllers can receive the tempdata, but only once, after the program is submitted back to the server again, it is impossible to obtain the tempdata object with the same value because it has been cleared in the session.

 

2. tempdata. Save (controllercontext, tempdataprovider)

This is the entire controller. Execute (...) The last operation in the lifecycle. Its function isSave New tempdataTo httpcontext. Base. Session. Code for the SAVE method:

public void Save(ControllerContext controllerContext, ITempDataProvider tempDataProvider) {            if (_modifiedKeys.Count > 0) {                // Apply change tracking.                foreach (string x in _initialKeys) {                    if (!_modifiedKeys.Contains(x)) {                        _data.Remove(x);                    }                }                // Store the dictionary                tempDataProvider.SaveTempData(controllerContext, _data);            }        }

We have mentioned the importance of _ initialkeys and _ modifiedkeys. Their functions will be shown here,

  • _ Initialkeys:All key values stored in tempdata before the action is executed. If a new key-value pair is inserted into tempdata during the action execution, the value in the _ initialkeys object will not be affected.
  • _ Modifiedkeys:During action execution, if a new key-value pair is inserted into tempdata, the new key is inserted into the _ modifiedkeys object.

In the Save method, first determine the number of elements in the _ modifiedkeys object and whether new key-value pairs are inserted into tempdata, foreach and the following if statements Delete useless key-value pair data from tempdata, and finally call tempdataprovider. savetempdata (controllercontext, _ DATA) method, save tempdata in httpcontextbase. session.

Note:During the loading of tempdata, the data in the last defined tempdata is put into _ data. Here, the foreach and if statements are used to remove key-value pairs that no longer need to be passed, make sure that only the key-value pairs generated during this action are retained in tempdata.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.