I have a Web API method:
public List<Task> GetTasks([FromUri] TaskFilter filter)
{
}
The method has parameter with list of nullable identifiers:
public class TaskFilter
{
public IList<int?> Assignees { get; set; }
}
When I call it:
GET /tasks?assignees=null
Server returns an error:
{
"message":"The request is invalid.",
"modelState": {
"assignees": [ "The value 'null' is not valid for Nullable`1." ]
}
}
It works only if I pass empty string:
GET /tasks?assignees=
But standard query string converters (from JQuery, Angular, etc) do not work with nulls in such way.
How to make ASP.NET to interpret 'null'
as null
?
Upd: The query string can contain several identifiers, e.g.:
GET /tasks?assignees=1&assignees=2&assignees=null
Upd2: JQuery converts nulls in array to empty strings, and ASP.NET interprets them as null. So the question is about calling WebAPI from Angular 1.6 ($HttpParamSerializerProvider
)
Upd3: I know about workarounds, but I do not ask for them. I want a solution for specific problem:
- It is a GET method
- Method accepts a list from Uri
- A list can contain
null
values - It should be
List<int?>
because API docs are generated automatically, and I do not want to see text array as parameter type - By default ASP.NET expects empty strings for null values (
JQuery.param
works in that way) - But some client libraries (e.g. Angular) does not convert
null
array items to empty strings
You can create a custom model bind for this specific type, inherithing from DefaultModelBinder, for sample:
Finally we need to inform the controller as to the binding we want it to use. This we can specify using attributes
as below:
For more reference check this link on Custom Model Binders. Hope, this solves your problem . Thanks
Finally, I found a solution using custom value provider:
And specify it in Web API action: