Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make GET request with a complex object?

I try to make GET request via WebApi with complex object. Request is like this:

[HttpGet("{param1}/{param2}")]
public async Task<IActionResult> GetRequest(string param1, int param2, [FromBody] CustomObject[] obj)
{
    throw new NotImplementException();
}

Where CustomObject is:

[DataContract]
public class CustomeObject
{        
    [DataMember]
    public string Name { get; set; }
    [DataMember]
    public string Email { get; set; }
}

How do I compose a valid GET request?

like image 741
Admiral Land Avatar asked May 07 '18 13:05

Admiral Land


People also ask

How do I pass complex type in Web API?

Best way to pass multiple complex object to webapi services is by using tuple other than dynamic, json string, custom class. No need to serialize and deserialize passing object while using tuple. If you want to send more than seven complex object create internal tuple object for last tuple argument.


2 Answers

[FromBody] CustomObject[] obj ... GET request has no message body and thus you should change it to FromUri.

Sure, take a look at Documentation

public class GeoPoint
{
    public double Latitude { get; set; } 
    public double Longitude { get; set; }
}

public ValuesController : ApiController
{
    public HttpResponseMessage Get([FromUri] GeoPoint location) { ... }
}

Request would be like below, essentially you pass the entire object data as query string

http://localhost/api/values/?Latitude=47.678558&Longitude=-122.130989

An array of object example can be found in another post pass array of an object to webapi

like image 130
Rahul Avatar answered Nov 15 '22 09:11

Rahul


If your complex object is defined by the server, you can model bind to it through the URI and dot notate the properties in the routing template. My advice is to keep this model to one level of properties. You can bind to more complex objects, but you'll quickly find yourself having to write your own model binder.

Note that your argument decorator will need to be changed to [FromUri] to bind a complex object through the Uri. Servers are not required to support GET bodies and most do not.

public class CustomObject
{ 
    public string Name { get; set; }
    public string Email { get; set; }
}

[HttpGet]
[Route("{foo.Name}/{foo.Email}")]
public HttpResponseMessage Get([FromUri]CustomObject foo)
{
   //...body
  return Request.CreateResponse(HttpStatus.OK, foo);
} 
like image 45
K. Alan Bates Avatar answered Nov 15 '22 09:11

K. Alan Bates