博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
WebApi用JilFormatter处理客户端序列化的字符串加密,之后在服务端解析。
阅读量:4703 次
发布时间:2019-06-10

本文共 5124 字,大约阅读时间需要 17 分钟。

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

 

转载于:https://www.cnblogs.com/Early-Bird/p/8031321.html

你可能感兴趣的文章
poj 3009 Curling 2.0(dfs)
查看>>
新浪微博客户端(10)-切换多个fragment
查看>>
新浪微博客户端(12)-判断当前软件是否是新版本(是否显示新特性)
查看>>
线段树1——神奇的数据结构
查看>>
jquery的一些技巧总结
查看>>
使用SQLite方式存储数据
查看>>
一个强大的UI node 抽象
查看>>
MVC,MVP 和 MVVM 的图示
查看>>
openwrt opkg update wget returned 4 wget returned 1
查看>>
.net + Android 通信
查看>>
C#dataset中数据导出到excel
查看>>
node和yarn
查看>>
hdu 4325
查看>>
移动端 html基值(转载)
查看>>
开源框架 系统
查看>>
积木艺术 (Cubist Artwork,Tokyo 2009,LA 4636)
查看>>
lvs+keepalived实现高可用群集配置详解
查看>>
Java连接MySQL数据库——含详细步骤和代码
查看>>
[平面文件源 [1]] 错误: 数据转换失败。列“列 1”的数据转换返回状态值 4 和状态...
查看>>
漫谈二分查找-Binary Search (转)
查看>>