Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IHttpActionResult result fail to bind request body parameter when parameters are defined directly as methods arguments instead of a model

When i put an array of Guids as an argument directly in my web api action result it doesnt find any of my guids which are in the request body and bind them e.g.

[HttpPost]
public IHttpActionResult AddStores([FromBody]Guid[] Ids)
{
   ...            
}

ids comes through as null although i do include ids it as an array of guids in my request body.

Only when i put ids inside a model then the model binder actually finds my ids in the request body.

e.g.

public class AddStoresRequest
{
    public Guid[] Ids { get; set; }
}


[HttpPost]
public IHttpActionResult AddStoreUser(AddStoresRequest request)
{
     ...            
}

In this case it does find the ids correctly. Why does this anomaly occur? Why does the model binder fail when i use Ids as an argument directly in my methods parameters?

I don't use the model when i build the request... i just put an array called Ids in the request body.

like image 799
Harry Avatar asked Dec 06 '25 02:12

Harry


1 Answers

by default when Guid[] Ids is added to request Your json serializer maps it to something like this:

{
   "Ids":["58b84557-1899-4354-b5ac-1d97c2b95e1b", "db7106d7-ba8a-44cc-b34d-90bec9b2ca3f"]
}

Thats why You have to use 2nd implemantation of action.

If You want to use 1st implemantation You must send something like this in body:

["58b84557-1899-4354-b5ac-1d97c2b95e1b", "db7106d7-ba8a-44cc-b34d-90bec9b2ca3f"]

You have to use custom serialization, or JArray to achive this.

like image 86
garret Avatar answered Dec 08 '25 16:12

garret



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!