Sending complex objects via HttpGet

2

I have a search method in my WebApi, as it is a search, I used [HttpGet] , as a parameter of this method, I pass an object with the filter options I want, for example:

public class ParametrosBusca {
    public string nome { get; set; }
    public DateTime dataInicial { get; set; }
    public DateTime dataFinal { get; set; }
}

The method declaration:

[HttpGet]
public JsonResult Buscar(ParametrosBusca parametros) {
   //...//
}

When calling my Api, passing the parameter, my object is not deserialized, but its I change the method to receive the parameter of type string I get it correctly and I can deserialize correctly, like this:

[HttpGet]
public JsonResult Buscar (string parametros) {
    var teste = new JavaScriptSerializer().Deserialize<ParametrosBusca>(parametros);
    //...//
}

If I use [HttpPost] , my parameter is also deserialized correctly.

My question, can not I pass complex objects in methods of type HttpGet ?

    
asked by anonymous 13.07.2017 / 14:40

1 answer

4

A Parameter binding of the Web API works as follows:

  • If the parameter is a simple type, the Web API tries to get the value of the URI. Simple types include the primitive .NET types ( int , bool , double , and so on), plus TimeSpan , DateTime Guid , decimal and string , in addition to any type with a types that can be converted from a string.

  • For complex types, the Web API tries to read the value of the body of the request

The problem is that the GET method can not have a body and all values are encoded in the URI. Therefore, it is necessary to force the Web API to read a complex URI type.

To do this, you can add the [FromUri] attribute to the:

[HttpGet]
public JsonResult Buscar([FromUri] ParametrosBusca parametros)
    
13.07.2017 / 15:01