.NET CORE 2.1升级到3.1,遇到api参数严格验证的问题

比如,后端api的某个参数为int,前端传入参数"123",在2.1项目时是可以获取到的。

但是升级到3.1后,可能改代码时去掉了某些东西,导致参数获取为null。

 

 

问题的根源应该是系统自带的system.txt.json没法将字符串转为文字。

 

解决办法1:

新建一个类

using System;
using System.Buffers;
using System.Buffers.Text;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace Mobile.Core.Common
{
    public class IntToStringConverter : JsonConverter<int>
    {
        public override int Read(ref Utf8JsonReader reader, Type type, JsonSerializerOptions options)
        {
            if (reader.TokenType == JsonTokenType.String)
            {
                ReadOnlySpan<byte> span = reader.HasValueSequence ? reader.ValueSequence.ToArray() : reader.ValueSpan;
                if (Utf8Parser.TryParse(span, out int number, out int bytesConsumed) && span.Length == bytesConsumed)
                {
                    return number;
                }
                if (Int32.TryParse(reader.GetString(), out number))
                {
                    return number;
                }
            }
            return reader.GetInt32();
        }
        public override void Write(Utf8JsonWriter writer, int value, JsonSerializerOptions options)
        {
            writer.WriteStringValue(value.ToString());
        }
    }

}

startup文件中

services.AddControllers().AddJsonOptions(options =>
{
    options.JsonSerializerOptions.Converters.Add(new IntToStringConverter());
});

 

 

 

解决办法2:

使用newtonsoft替换掉默认的json序列化组件

参考:https://www.cnblogs.com/shapman/p/12232640.html

官网文档:https://docs.microsoft.com/zh-cn/aspnet/core/web-api/advanced/formatting?view=aspnetcore-5.0

 

posted @ 2021-12-22 14:06  老铁你咋这么肥  阅读(186)  评论(0编辑  收藏  举报