How to configure Web API with multiple Get

4

I need to provide in my web api three forms of query: First Get with all records "GetAll", the second GET by the id and a third GET with filtering options, sent by the client eg Name contains the letter " the "and address contains the word" bridge ", I thought of sending by queryString, but it does not hit the correct action, incomplete example of how I thought of getting the Get filtered:

public HttpResponseMessage GetFiltrados() {
    string condicao = "";
    string[] filtros = Request.RequestUri.Query.Substring(1).Split('&');
    foreach (var filtro in filtros) {
        condicao += "";
    }
    if (reg != null) {
        return Request.CreateResponse(HttpStatusCode.OK, reg);
    } else {
        return Request.CreateResponse(HttpStatusCode.NotFound, "Registro não encontrado");
}

}

How can I create these three Get methods? I'm doing the right way with Get with filters to default REST?
Ps .: My POST did in the standard, everything in JSON, but in GET did not know how to solve the filtering.

    
asked by anonymous 15.07.2016 / 19:55

1 answer

7

I do not quite understand, but its GET with the optional parameters can be this way:

[HttpGet,Route("api/Pessoas/ListarFiltrados")]
public IHttpActionResult ListarFiltrados(string? Nome= null, string? Sobrenome= null, int? idade= null)  
{
    var pessoas = db.Pessoas(Nome, Sobrenome, idade);
    return Ok(pessoas );
}

Note that in front of each type has the ? sign which allows the past attributes to be null.

The URL would look like this:

../api/ListarFiltrados?Nome=Diego&Sobrenome=Augusto&idade=23 

Another option would be to use ParameterBinding where you can pass an integer object to your Endpoint :

public IHttpActionResult ListarFiltrados([FromUri]Pessoa pessoa) {...}

Model Person:

public class Pessoa
{
    public string Nome{ get; set; }
    public string Sobrenome{ get; set; }
    public int? Idade{ get; set; }
}

The queryString remains the same.

    
15.07.2016 / 20:29