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序列化器,然后分别进行反序列化操作。你可以根据自己的需求,自定义更多的序列化器。

相关内容

热门资讯

辅助透视!陕麻圈辅助开挂软件,... 辅助透视!陕麻圈辅助开挂软件,hhpoker怎么防作弊(辅助挂)详细开挂辅助工具;无需打开直接搜索加...
透视能赢!广东雀神智能插件安装... 透视能赢!广东雀神智能插件安装可使用,wepoker私人局辅助(辅助挂)详细开挂辅助脚本您好:广东雀...
透视安卓版!柳州八一字牌辅助,... 透视安卓版!柳州八一字牌辅助,拱趴大菠萝挂哪里(辅助挂)详细开挂辅助脚本;无需打开直接搜索打开薇:1...
透视脚本!浙江游戏大厅辅助器,... 透视脚本!浙江游戏大厅辅助器,wpk私人局辅助是真的吗(辅助挂)详细开挂辅助器 了解更多开挂安装加(...
透视透明!卡五星辅助工具,we... 透视透明!卡五星辅助工具,wepoker到底有没有透视(辅助挂)详细开挂辅助器 了解更多开挂安装加(...
透视脚本!约局吧可以看到别人的... 大家好,今天小编来为大家解答约局吧可以看到别人的底牌这个问题咨询软件客服可以免费测试直接加微信(13...
透视透明!多乐小程序游戏破解器... 多乐小程序游戏破解器开挂教程视频分享装挂详细步骤在当今的网络游戏中,多乐小程序游戏破解器作为一种经典...
透视真的!葫芦娃七子连心攻略,... 透视真的!葫芦娃七子连心攻略,hhpoker开挂教程(辅助挂)详细开挂辅助器1、下载安装好葫芦娃七子...
透明肯定!福建天天开心一直输怎... 大家好,今天小编来为大家解答福建天天开心一直输怎么办这个问题咨询软件客服可以免费测试直接加微信(13...
透明教学!八闽掌上辅助,pok... 透明教学!八闽掌上辅助,poker红龙辅助(辅助挂)详细开挂辅助挂 了解更多开挂安装加(136704...