1. 程式人生 > >WebApi用JilFormatter處理客戶端序列化的字符串加密,之後在服務端解析。

WebApi用JilFormatter處理客戶端序列化的字符串加密,之後在服務端解析。

template images out log return es2017 reading option 序列

本文有改動,參考原文: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<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); } } }

在這裏獲取到 客戶端傳來的字符串 解密處理:

       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 }
            );


            
        }
    }

WebApi用JilFormatter處理客戶端序列化的字符串加密,之後在服務端解析。