Sending complex objects via Httpget

Asked

Viewed 1,152 times

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 declaration of the method:

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

When calling my Api by passing the parameter, my object is not deserialized, however, if I change the method to receive the string type parameter I receive it correctly and can deserialize it correctly, this way:

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

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

My question, can’t pass complex objects in methods like HttpGet?

1 answer

4


To parameter binding Web API works as follows:

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

  • For complex types, the Web API tries to read the value of body of requisition (request body).

The problem is that the method GET can’t 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 attribute [FromUri] to the parameter:

[HttpGet]
public JsonResult Buscar([FromUri] ParametrosBusca parametros)
  • 1

    Show.. Thank you for the reply.

  • 1

    @merchant has some advantage in using [Fromuri] no get instead of making a post?

  • 2

    @Aesir I would not say that there is advantage or disadvantage, but rather that it is important to maintain the consistency of the objective of the requests. GET is recommended to receive data from the server, while POST is used to send information in order to make it persistent.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.