Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core API not accepting null value for a nullable type

I have a GET request API endpoint that receives a request View Model with a Nullable property like this:

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
    }

but when I make a get request for MakeId with a null value, The API is not accepting null value for this nullable type.

this is my get request: https://localhost:44311/api/model/getlist?MakeId=null

I get the following error:

The value 'null' is not valid for MakeId.

like image 560
Zeeshan Adil Avatar asked Mar 28 '19 13:03

Zeeshan Adil


People also ask

How do I pass a null parameter in Web API?

Simply add parameterName = null in your route parameter. Another option is add an overload. Have 2 function names receive different parameters.

How do you pass a nullable value?

You can't pass a primitive as null. There's two ways to do this- first is to make the function take Double- the class version of a double. The other is to pass in some unused value, such as -1, to mean null. That requires there to be a reasonable default value though.

What is the default value of nullable type in C#?

The default value of a nullable value type represents null , that is, it's an instance whose Nullable<T>. HasValue property returns false .

How do you define a nullable class in C#?

In C# and Visual Basic, you mark a value type as nullable by using the ? notation after the value type. For example, int? in C# or Integer? in Visual Basic declares an integer value type that can be assigned null . The Nullable class provides complementary support for the Nullable<T> structure.


2 Answers

MakeId is a Nullable<uint> but MakeId=null in the query string null is just a string value which can not be parsed as uint. just omit it from your request to make it null:

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

You can do something like this to include makeid if it's not null:

string url = $"https://localhost:44311/api/model/getlist(makeid == null?"":"?makeid=" + makeid)";
like image 110
Ashkan Mobayen Khiabani Avatar answered Sep 19 '22 06:09

Ashkan Mobayen Khiabani


It is actually receiving the string "null" and can not convert it to uint.

The value would be null if you omit it.

like image 21
Alen Genzić Avatar answered Sep 22 '22 06:09

Alen Genzić