WebApi用JilFormatter处理客户端序列化的字符串加密,之后在服务端解析。

2021-07-27 06:55

阅读:619

本文有改动,参考原文:https://www.cnblogs.com/liek/p/4888201.html                                       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 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); } } }   在这里获取到 客户端传来的字符串 解密处理:    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);                }            }            catch            {                return null;            }        }  WebApi配置加: GlobalConfiguration.Configuration.Formatters[0] = new JilFormatter(); public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API 配置和服务 // 将 Web API 配置为仅使用不记名令牌身份验证。 config.SuppressDefaultHostAuthentication(); config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType)); //GlobalConfiguration.Configuration.Formatters; //config.Formatters.Clear(); //config.Formatters.Add(new CustomNamespaceXmlFormatter()); var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter; Console.WriteLine(json); json.UseDataContractJsonSerializer = true; var xml = GlobalConfiguration.Configuration.Formatters.XmlFormatter; xml.UseXmlSerializer = true; GlobalConfiguration.Configuration.Formatters[0] = new JilFormatter(); // Web API 路由 config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } }  


评论


亲,登录后才可以留言!