Using WCF DataContract in MVC SessionState using AppFabric cache

后端 未结 2 1711
南旧
南旧 2021-02-10 01:05

I have a Data Access Layer, a Service Layer, and a Presentation Layer. The Presentation Layer is ASP.NET MVC2 RTM (web), and the Service Layer is WCF (services). It\'s all .NET

2条回答
  •  北海茫月
    2021-02-10 01:44

    As an extension to the provided answer, I added these two methods to ease storing/retrieving the data.

        public static void Set(HttpSessionStateBase session, string key, T value)
        {
            session[key] = new Wrapper(value);
        }
    
        public static T Get(HttpSessionStateBase session, string key)
        {
            object value = session[key];
            if (value != null && typeof(T) == value.GetType())
            {
                return (T) value;
            }
            Wrapper wrapper = value as Wrapper;
            return (T) ((wrapper == null) ? null : wrapper.Value);
        }
    

    This makes it a little easier to set/get values from the session:

        MyDataContract c = ...;
        Wrapper.Set(Session, "mykey", c);
        c = Wrapper.Get(Session, "mykey");
    

    To make it even easier, add extension methods:

    public static class SessionWrapperEx
    {
        public static void SetWrapped(this HttpSessionStateBase session, string key, T value)
        {
            Wrapper.Set(session, key, value);
        }
    
        public static T GetWrapped(this HttpSessionStateBase session, string key)
        {
            return Wrapper.Get(session, key);
        }
    }
    

    And use as below:

        MyDataContract c = ...;
        Session.SetWrapped("mykey", c);
        c = Session.GetWrapped("mykey");
    

提交回复
热议问题