Re: Получить ViewState
От: TK Лес кывт.рф
Дата: 17.08.02 13:56
Оценка: 61 (3)
Здравствуйте Igor Soukhov, Вы писали:

IS>Хочу странного — получить данные сериализованне данные из ViewState (уже заенкоденные)

IS>в виде стрима, raw bytes. или строки — все равно. Где копать.
IS>То какую ф-ю (у контрола, формы, или ...) надо переопределить что-бы к этому место весь
IS>ViewState был уже тепленький и я мог, например подменить его перед отправкой на клиетна.
IS>(соответсвенно интересует и обратная операция — получить вьюстейт отправленный с клиента
IS>при постбеке). Интересуют способы реализации на уровне

IS>1)страницы/контролов

IS>2)реализации IHTTPModule/IHttpHandler


Для страницы нужно перекрыть SavePageStateToPersistenceMedium/Load...

А вот собственно пример сохранения ViewState в базу SQL сервера (как получить raw bytes наверное можно разобраться ):
    public class ViewStateModule : IHttpModule
    {
        private SqlConnection stateConnection;
        private System.Web.HttpApplication application;

        public SqlConnection Connection
        {
            get
            {
                stateConnection.ConnectionString = System.Configuration.ConfigurationSettings.AppSettings["ViewStateDatabase"];
                return stateConnection;
            }
        }

        public ViewStateModule()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        public void Init(System.Web.HttpApplication context)
        {
            application = context;
            System.Collections.Specialized.NameValueCollection appSettings = System.Configuration.ConfigurationSettings.AppSettings;
            stateConnection = new SqlConnection(appSettings["ViewStateDatabase"]);

            SessionStateModule sessionState = application.Modules["Session"] as SessionStateModule;
            
            sessionState.Start += new System.EventHandler(Session_Start);
            sessionState.End += new System.EventHandler(Session_End);
        }

        public void Dispose()
        {
            SessionStateModule sessionState = application.Modules["SessionState"] as SessionStateModule;
            
            sessionState.Start -= new System.EventHandler(Session_Start);
            sessionState.End -= new System.EventHandler(Session_End);
        }

        private void Session_End(object sender, EventArgs e)
        {
            SqlConnection stateConnection = Connection;

            using (stateConnection)
            {
                stateConnection.Open();
                
                SqlCommand sqlDrop = stateConnection.CreateCommand();
                sqlDrop.CommandText = "DropSession";
                sqlDrop.CommandType = CommandType.StoredProcedure;
                sqlDrop.Parameters.Add("@SessionCookie", SqlDbType.VarChar, 50).Value = application.Session.SessionID;

                sqlDrop.ExecuteNonQuery();
            }
        }

        private void Session_Start(object sender, EventArgs e)
        {
        }

        public static System.Guid SavePageViewState(HttpContext context, object state)
        {
            ViewStateModule _this = ViewStateModule.Current;
            System.Guid Result = System.Guid.Empty;

            if (_this != null)
            {                
                using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
                {
                
                    System.Web.UI.LosFormatter losf = new System.Web.UI.LosFormatter();
                    losf.Serialize(stream, state);

                    SqlConnection stateConnection = _this.Connection;

                    using (stateConnection)
                    {
                        stateConnection.Open();

                        SqlCommand sqlSave = _this.stateConnection.CreateCommand();
                        sqlSave.CommandText = "SavePageViewState";
                        sqlSave.CommandType = CommandType.StoredProcedure;
                        sqlSave.Parameters.Add("@SessionCookie", SqlDbType.VarChar, 50).Value = _this.application.Session.SessionID;
                        sqlSave.Parameters.Add("@ViewState", SqlDbType.Image).Value = stream.ToArray();
                                                
                        Result = new System.Guid(sqlSave.ExecuteScalar().ToString());
                    }
                }
            }

            return Result;
        }

        public static object LoadPageViewState(HttpContext context, System.Guid stateId)
        {
            ViewStateModule _this = ViewStateModule.Current;
            object Result = null;

            if (_this != null)
            {
                SqlConnection stateConnection = _this.Connection;

                using (stateConnection)
                {                    
                    stateConnection.Open();

                    SqlCommand sqlLoad = stateConnection.CreateCommand();
                    sqlLoad.CommandText = "LoadPageViewState";
                    sqlLoad.CommandType = CommandType.StoredProcedure;
                    sqlLoad.Parameters.Add("@RequestStamp", SqlDbType.UniqueIdentifier).Value = stateId;

                    using (System.Data.SqlClient.SqlDataReader reader = sqlLoad.ExecuteReader())
                    {
                        if (reader.Read())
                        {
                            System.IO.MemoryStream stream = new System.IO.MemoryStream(reader[0] as byte []);

                            System.Web.UI.LosFormatter losf = new System.Web.UI.LosFormatter();
                            Result = losf.Deserialize(stream);
                        }
                    }
                }
            }

            return Result;
        }

        public static ViewStateModule Current
        {
            get
            {
                return HttpContext.Current.ApplicationInstance.Modules["ViewState"] as ViewStateModule;
            }
        }
    }
Если у Вас нет паранойи, то это еще не значит, что они за Вами не следят.
 
Подождите ...
Wait...
Пока на собственное сообщение не было ответов, его можно удалить.