ASP.NET Core API不接受可为空的类型的空值

时间:2019-03-28 13:57:09

标签: c# asp.net-core asp.net-core-webapi

我有一个GET请求API端点,该端点接收具有如下Nullable属性的请求视图模型:

public class ModelRequestVM : BaseRequestVM
    {
        #region Properties and Data Members
        public uint ModelId { get; set; }
        public uint? MakeId { get; set; }
        public string MakeName { get; set; }
        public string ModelName { get; set; }
        public uint? ExternalModelId { get; set; }

        #endregion
    }

但是当我请求使用MakeId值的null的获取请求时,API不接受这种可空类型的null值。

这是我的获取请求:https://localhost:44311/api/model/getlist?MakeId=null

我收到以下错误:

The value 'null' is not valid for MakeId.

2 个答案:

答案 0 :(得分:6)

MakeId是Nullable<uint>,但是查询字符串MakeId=null中的null只是一个字符串值,不能将其解析为uint。只需从您的请求中将其忽略即可使其为空:

https://localhost:44311/api/model/getlist

如果不为null,则可以执行以下操作以包含makeid:

string url = $"https://localhost:44311/api/model/getlist(makeid == null?"":"?makeid=" + makeid)";

答案 1 :(得分:4)

它实际上正在接收字符串“ null”,并且无法将其转换为uint

如果省略,则该值为null。

相关问题