Using WCF DataContract in MVC SessionState using AppFabric cache

后端 未结 2 1715
南旧
南旧 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 02:05

    Without going the full blown route of A or B, could you just make a generic ISerializable wrapper object and put those in your SessionState?

        [Serializable]
        public class Wrapper : ISerializable
        {
            public object Value { get; set; }
    
            void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
            {
                if (Value != null)
                {
                    info.AddValue("IsNull", false);
                    if (Value.GetType().GetCustomAttributes(typeof(DataContractAttribute), false).Length == 1)
                    {
                        using (var ms = new MemoryStream())
                        {
                            var serializer = new DataContractSerializer(Value.GetType());
                            serializer.WriteObject(ms, Value);
                            info.AddValue("Bytes", ms.ToArray());
                            info.AddValue("IsDataContract", true);
                        }
                    }
                    else if (Value.GetType().IsSerializable)
                    {
                        info.AddValue("Value", Value);
                        info.AddValue("IsDataContract", false);
                    }
                    info.AddValue("Type", Value.GetType());
                }
                else
                {
                    info.AddValue("IsNull", true);
                }
            }
    
            public Wrapper(SerializationInfo info, StreamingContext context)
            {
                if (!info.GetBoolean("IsNull"))
                {
                    var type = info.GetValue("Type", typeof(Type)) as Type;
    
                    if (info.GetBoolean("IsDataContract"))
                    {
                        using (var ms = new MemoryStream(info.GetValue("Bytes", typeof(byte[])) as byte[]))
                        {
                            var serializer = new DataContractSerializer(type);
                            Value = serializer.ReadObject(ms);
                        }
                    }
                    else
                    {
                        Value = info.GetValue("Value", type);   
                    }
                }
            }
        }
    

提交回复
热议问题