NetCore3.1升级到Net5.0序列化方法过时问题

问题描述:Net5.0已经出来有段时间了,就琢磨的项目升级到5.0试一试的,按照方法,把项目sdk版本修改完后基本就算升级成功了,但是有个Redis序列化的方法有警告,提示这个

警告	SYSLIB0011	“BinaryFormatter.Serialize(Stream, object)”已过时:“BinaryFormatter serialization is obsolete and should not be used. See https://aka.ms/binaryformatter for more information.”

  打开微软的说明页面,大概意思就是随便将泛型的数据写入和读取内存,存在风险隐患。

解决方案:按照微软的提示,将方法换一下就哦了

        /// <summary>
        /// 序列化
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private static byte[] Serialize(object obj)
        {
            if (obj == null)
                return null;

            using var memoryStream = new MemoryStream();
            DataContractSerializer ser = new DataContractSerializer(typeof(object));
            ser.WriteObject(memoryStream, obj);
            var data = memoryStream.ToArray();
            return data;
        }

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="data"></param>
        /// <returns></returns>
        private static T Deserialize<T>(byte[] data)
        {
            if (data == null)
                return default(T);

            using var memoryStream = new MemoryStream(data);
            XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(memoryStream, new XmlDictionaryReaderQuotas());
            DataContractSerializer ser = new DataContractSerializer(typeof(T));
            var result = (T)ser.ReadObject(reader, true);
            return result;
        }

有个问题,就是要序列化的类,必须多加几个处理,比如下面这样,当然不能保证我的解决办法就是最优的。。。

    [Serializable]
    [KnownType(typeof(AuthorizeActionModel))]
    [DataContract(Name = "Customer", Namespace = "http://www.contoso.com")]
    public class AuthorizeActionModel : IExtensibleDataObject
    {
        /// <summary>
        /// 菜单编号
        /// </summary>
        [DataMember]
        public string SysModuleId { set; get; }
        /// <summary>
        /// 链接地址
        /// </summary>
        [DataMember]
        public string PageLink { set; get; }

        private ExtensionDataObject extensionData_Value;

        public ExtensionDataObject ExtensionData
        {
            get
            {
                return extensionData_Value;
            }
            set
            {
                extensionData_Value = value;
            }
        }
    }

再附带一个小问题,就是docker镜像路径的变化

- docker pull mcr.microsoft.com/dotnet/core/aspnet:3.1
+ docker pull mcr.microsoft.com/dotnet/aspnet:5.0

参考地址:https://docs.microsoft.com/zh-cn/dotnet/api/system.runtime.serialization.datacontractserializer?view=net-5.0

https://stackoverflow.com/questions/12936713/web-api-error-the-objectcontent1-type-failed-to-serialize-the-response-body

 https://docs.microsoft.com/en-us/aspnet/core/migration/31-to-50?view=aspnetcore-5.0&tabs=visual-studio#update-the-target-framework

posted @ 2020-11-22 17:21  wangbg  阅读(2353)  评论(0编辑  收藏  举报