繁体   English   中英

请求model null in .NET core API if input json value integer

[英]Request model null in .NET core API if input json value integer

我有一个情况,我的API之一是.net WebAPI已转换为.netcore API。 .

这里的问题是针对我的旧 API ( Asp.net Web API),我的参数之一 MobileNo 如果我以字符串形式传递它或 integer 它接受它并进一步处理流程。

但在 (.Net Core API ) 中,它不会以这种方式发生。 如果我通过移动电话号码。 在字符串中它接受请求。 但如果传递数值,我会在 Model 中得到 null object。

提供了以下被接受的样本请求和被传递为 null 的请求

接受请求

{
"EmployeeCode":"1234"
"EmployeeName":"Test"
"MobileNo":"1234567890"
}

Null Model 通过

{
"EmployeeCode":"1234"
"EmployeeName":"Test"
"MobileNo":1234567890
}

我的 model 和 controller 代码如下

public class EmpRequest 
    { 
        public string EmployeeCode { get; set; } 
        public string EmployeeName { get; set; }
        public string MobileNo { get; set; }
}


[HttpPost]
        [ProducesResponseType(200)]
        [ProducesResponseType(500)]
        public async Task<IActionResult>APIGetEmployee([FromBody] EmpRequest reqModel)
        {
}

我试图转换 controller 中的值

Convert.Tostring(reqModel.MobileNo )

但它不起作用,因为 model 本身的要求是 null。

这是因为在您的 model 中,您将 mobileno 属性作为字符串,并且您想将 int 值传递给该属性。 如果您想将 Int 传递给它,您可以将 model 属性 MobileNo 转换为 Int。 当您传递 object 时数据值不匹配,这就是它返回 null 的原因。

请注意,它在 ASP.NET Core 3.0+ 项目中默认使用System.Text.Json进行 JSON 序列化和反序列化,并且它不允许字符串属性使用非字符串 JSON 值。

为了达到您的要求并解决问题,正如@Oliver 在评论中提到的,您可以尝试实现和使用自定义 JsonConverter,如下所示。

public class ConverterForMobileNo : JsonConverter<string>
{
    public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        if (reader.TokenType == JsonTokenType.Number)
        {
            int value = reader.GetInt32();
            return value.ToString();
        }
        else if (reader.TokenType == JsonTokenType.String)
        {
            return reader.GetString();
        }

        throw new JsonException();
    }

    public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options)
    {
        writer.WriteStringValue(value);
    }
}

应用 jsonconverter

[JsonConverter(typeof(ConverterForMobileNo))]
public string MobileNo { get; set; }

此外,Newtonsoft.Json 似乎允许字符串属性的非字符串 JSON 值,您也可以尝试安装Microsoft.AspNetCore.Mvc.NewtonsoftJson NuGet package 以添加对基于 Newtonsoft.Json 的功能的支持。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM