https://www.cnblogs.com/tonykan/p/3963875.html
成果配景:WebApi 客户端 一个Model 序列化为string类型,想将其加密之后再Post随处事端,在处事端解析出来再措置惩罚惩罚。
Jil.dll 安置:
然后: 选择项目,输入 Install-Package Jil 回车。
然后创建一个JilFormatter类,代码如下:
using Jil; using OLW.Common.Helpers; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Web; using System.Xml.Serialization; namespace WxPayWebApi.Common { public class JilFormatter : MediaTypeFormatter { private readonly Options _jilOptions; private MethodInfo _method; public JilFormatter() { //要序列化的时间格局 _jilOptions = new Options(dateFormat: DateTimeFormat.ISO8601); //媒体类型 SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/test")); //插手 UTF8Encoding 编码 SupportedEncodings.Add(new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true)); //插手 UnicodeEncoding 编码 SupportedEncodings.Add(new UnicodeEncoding(bigEndian: false, byteOrderMark: true, throwOnInvalidBytes: true)); } //判断是否反序列化类型 public override bool CanReadType(Type type) { if (type == null) { throw new ArgumentNullException("type"); } return true; } //判断是否序列化类型 public override bool CanWriteType(Type type) { if (type == null) { throw new ArgumentNullException("type"); } return true; } // 异步反序列化一个指定类型的东西。 public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, System.Net.Http.HttpContent content, IFormatterLogger formatterLogger) { return Task.FromResult(DeserializeFromStream(type, readStream)); } private object DeserializeFromStream(Type type, Stream readStream) { try { StreamReader sr = new StreamReader(readStream); string text = sr.ReadToEnd(); string s = EncrypAndDecrypHelper.Decrypt(text); using (StringReader ssr = new StringReader(s)) { XmlSerializer xmldes = new XmlSerializer(type); return xmldes.Deserialize(ssr); } //using (var reader = new StreamReader(readStream)) //{ //return JSON.Deserialize(reader, type, _jilOptions); //} } catch { return null; } } // 异步序列化一个指定类型的东西。 public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, System.Net.Http.HttpContent content, TransportContext transportContext) { var streamWriter = new StreamWriter(writeStream); JSON.Serialize(value, streamWriter, _jilOptions); streamWriter.Flush(); return Task.FromResult(writeStream); } } }
在这里获取到 客户端传来的字符串 解密措置惩罚惩罚: