I’m developing a WebApi rest revice solution and would like to pass multiple complex type as url parameters. I need to pass two objects of personal data. Personal data contains FullName and Id.
public class Foo
{
public string FullName { get; set; }
public string Id { get; set; }
}
I was expecting that I could call my REST service with url similar to this:
http://localhost:53088/values/GetByFoo/?foo1={"FullName":"Name 1","Id":"1"}&foo2={"FullName":"Name 2","Id":"2"}
So I’ve coded ValuesController.cs like this:
[HttpGet]
public List<Foo> GetByFoo2([FromUri] Foo foo1, [FromUri] Foo foo2)
{
List<Foo> foos = new List<Foo>();
foos.Add(foo1);
foos.Add(foo2);
return foos;
}
Unfortunately parameters in [HttpGet] methods are always NULL
As it was not working I’ve tried to start with one parameter and this is what I have achieved so far:
ValuesController.cs
[HttpGet]
public Foo GetByFoo([FromUri] Foo foo)
{
return foo;
}
I could only get right values in this case: /Values/GetByFoo?FullName=NAME1&Id=1
In this case foo parameter is always NULL /values/GetByFoo/?foo={"FullName":"Name 1","Id":"1"}
Then I’ve thought of using one parameter, containing both foo1 and foo2 properties and make this get request:
/values/GetByFooPair/?foopair={"Foo1":{"FullName":"Name 1","Id":"1"},"Foo2":{"FullName":"Name 2","Id":"2"}}
public class FooPair
{
public Foo Foo1 { get; set; }
public Foo Foo2 { get; set; }
}
But it’s not working either, controller method parameter are always null.
By the other hand , if I use HttpPost method and make an ajax request using jQuery, parameters are correct and contains expected values.
[HttpPost]
public FooPair GetByFooPairPost([FromBody] FooPair foopair)
{
return foopair;
}
Is it possible to pass several complex type parameters through url?
What am I missing? What am I doing wrong?
You need to change it to a [HttpPost] if you want to handle complex objects.
You can do it like this:
http://localhost:53088/values/GetByFoo?foo1.fullName=Fullname1&foo1.id=ID1&foo2.fullName=Fullname2&foo2.id=ID2
Tested on WebAPI 2.2 (nuget package version 5.2.3) in .NET framework 4.5.2.
However, just as Shyju and codeMonkey have pointed out, I would not recommend this if the objects have any bit of complexity. HttpPost accepts any amount of content in the body, whereas the querystring length is limited. Also you'll get automatic serialization to a correct JSON format from Javascript when using the body, as in comparison here, you'll have to do the serialization yourself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With