Nov 30, 2011

Custome TempData Provider

Life span of TempData object is only till the subsequent request, or until the item is removed explicitly. This is useful when you want to pass data to another view that you will be redirecting to, rather than rendering to. By default, TempData is stored in the session using SessionStateTempDataProvider. So if you want to switch away from the default Session-State Mode, and use State Server Mode or SQL Server Mode, you need to store TempData objects which can be serializable.

You can also specify a custome temp data provider by setting TempDataProvider property of the controller.
public EmployeeController()
        {
            TempDataProvider = new CustomeTempDataProvider();
        }
 

CustomeTempDataProvider just need to implement ITempDataProvider. Refer to the sample code. In this example I am saving/loadion temp data to/from HttpContext.Current.Cache.

public class CustomeTempDataProvider : ITempDataProvider

    {
        internal string TempDataSessionStateKey = "__ControllerTempData";

        public IDictionary LoadTempData(ControllerContext controllerContext)
        {
            string userIdentifier = controllerContext.HttpContext.Request.UserHostAddress;

            HttpContext current = HttpContext.Current;
            if (current != null)
            {
                Dictionary dictionary = HttpContext.Current.Cache[TempDataSessionStateKey + userIdentifier] as Dictionary;
                if (dictionary != null)
                {
                    HttpContext.Current.Cache.Remove(TempDataSessionStateKey + userIdentifier);
                    return dictionary;
                }
            }
            return new Dictionary(StringComparer.OrdinalIgnoreCase);
        }

        public void SaveTempData(ControllerContext controllerContext, IDictionary values)
        {
            string userIdentifier = controllerContext.HttpContext.Request.UserHostAddress;

            if (controllerContext == null)
            {
                throw new ArgumentNullException("controllerContext");
            }
            HttpContext current = HttpContext.Current;
            bool flag = values != null && values.Count > 0;
            if (current == null)
            {
                if (flag)
                {
                    throw new InvalidOperationException("SessionStateTempDataProvider_SessionStateDisabled");
                }
            }
            else
            {
                if (flag)
                {
                    HttpContext.Current.Cache[TempDataSessionStateKey + userIdentifier] = values;
                    return;
                }
                if (HttpContext.Current.Cache[TempDataSessionStateKey + userIdentifier] != null)
                {
                    HttpContext.Current.Cache.Remove(TempDataSessionStateKey + userIdentifier);
                }
            }
        }
    }
 

No comments:

Post a Comment