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

Posted 歌·颂

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了WebApi用JilFormatter处理客户端序列化的字符串加密,之后在服务端解析。相关的知识,希望对你有一定的参考价值。

本文有改动,参考原文: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处理客户端序列化的字符串加密,之后在服务端解析。的主要内容,如果未能解决你的问题,请参考以下文章

C#进阶系列——WebApi 异常处理解决方案

WebAPI错误处理:如何简化调试

用MVC5+EF6+WebApi 做一个考试功能 前端主题

如何使用 WebAPI 处理图像

带有协议缓冲区的 ASP.NET WebApi - 错误处理

WEBapi如何 去除 ASP.NET_SessionId 这个返回的Cookies啊?