ASP.Net Core 2.2 - 输入和输出的序列化器设置分离
创始人
2024-09-14 15:30:52
0

在ASP.Net Core 2.2中,可以通过自定义序列化器来设置输入和输出的序列化器分离。下面是一个包含代码示例的解决方法:

  1. 首先,创建一个自定义的JsonInputFormatter类,继承自AspNetCore提供的JsonInputFormatter类:
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.Net.Http.Headers;
using Newtonsoft.Json;
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;

namespace YourNamespace
{
    public class SeparateSerializerInputFormatter : JsonInputFormatter
    {
        public SeparateSerializerInputFormatter(JsonSerializerSettings serializerSettings, ArrayPool charPool, ObjectPoolProvider objectPoolProvider, MvcOptions options, ILogger logger) : base(serializerSettings, charPool, objectPoolProvider, options, logger)
        {
        }

        public override async Task ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)
        {
            var request = context.HttpContext.Request;
            var contentType = context.HttpContext.Request.ContentType;
            var mediaType = new MediaType(contentType);

            var serializerSettings = new JsonSerializerSettings
            {
                ContractResolver = new DefaultContractResolver(),
                DateTimeZoneHandling = DateTimeZoneHandling.Utc,
                DateFormatHandling = DateFormatHandling.IsoDateFormat
            };

            if (mediaType.MatchesContentType(MediaTypeHeaderValue.Parse("application/xml")))
            {
                // Use XML deserializer for input
                var xmlSerializer = new XmlSerializer(typeof(YourInputModel));
                var inputModel = (YourInputModel)xmlSerializer.Deserialize(request.Body);
                return await InputFormatterResult.SuccessAsync(inputModel);
            }
            else if (mediaType.MatchesContentType(MediaTypeHeaderValue.Parse("application/json")))
            {
                // Use JSON deserializer for input
                var json = await new StreamReader(request.Body).ReadToEndAsync();
                var inputModel = JsonConvert.DeserializeObject(json, serializerSettings);
                return await InputFormatterResult.SuccessAsync(inputModel);
            }

            return await InputFormatterResult.FailureAsync();
        }
    }
}
  1. 然后,在Startup.cs文件中注册这个自定义的JsonInputFormatter类,替换掉默认的JsonInputFormatter:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using YourNamespace;

namespace YourNamespace
{
    public class Startup
    {
        // ...

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers(options =>
            {
                options.InputFormatters.Insert(0, new SeparateSerializerInputFormatter(new JsonSerializerSettings(), ArrayPool.Shared, ObjectPoolProvider.Create(), options, NullLogger.Instance));
            });
        }

        // ...
    }
}

这样就实现了输入和输出的序列化器设置分离。在自定义的JsonInputFormatter类中,根据请求的Content-Type来判断使用XML序列化器还是JSON序列化器,然后分别进行反序列化操作。你可以根据自己的需求,自定义更多的序列化器。

相关内容

热门资讯

6分钟辅助!hhpoker是真... 6分钟辅助!hhpoker是真的假的,hhpoker真的有透视吗,演示教程(真是有挂)1、每一步都需...
第七分钟辅助!we poker... 第七分钟辅助!we poker插件,we poker免费辅助器,手筋教程(有挂方式)暗藏猫腻,小编详...
七分钟辅助!aa poker辅... 七分钟辅助!aa poker辅助包,pokemmo脚本辅助器下载,讲义教程(有挂秘籍)1、pokem...
第四分钟辅助!wepoker辅... 第四分钟辅助!wepoker辅助器安装包定制,aapoker透视脚本,大纲教程(有挂总结)所有人都在...
第四分钟辅助!wpk透视辅助靠... 第四分钟辅助!wpk透视辅助靠谱吗,wepoker透视苹果系统,诀窍教程(有挂猫腻);运wepoke...
七分钟辅助!aapoker透视... 七分钟辅助!aapoker透视脚本入口,wejoker开挂,学习教程(有挂教程)1、打开软件启动之后...
第四分钟辅助!淘宝买wepok... 第四分钟辅助!淘宝买wepoker透视有用吗,wpk俱乐部怎么作弊,积累教程(有挂规律)1、下载好淘...
6分钟辅助!we-poker软... 6分钟辅助!we-poker软件,购买的wpk辅助在哪里下载,积累教程(有挂技巧)购买的wpk辅助在...
第2分钟辅助!如何下载wepo... 第2分钟辅助!如何下载wepoker安装包,newpoker怎么安装脚本,教程书教程(今日头条)1、...
4分钟辅助!wepoker钻石... 4分钟辅助!wepoker钻石怎么看底牌,wepoker辅助器有哪些功能,法门教程(有挂详细)该软件...