WebApi URL Path

1

I have a Rest service in WebApi, generated the controllers by the wizard that defined the answers in "api / {controller} / {id}", as the example of get by id:

 // GET: api/pessoas/5
        [ResponseType(typeof(pessoa))]
        public IHttpActionResult Getpessoa(int id)
        {
            pessoa pessoa = db.pessoa.Find(id);
            if (pessoa == null)
            {
                return NotFound();
            }

            return Ok(pessoa);
        }

So far so good, but now I need to consult for the cnpj of people I tried to do so only he does not understand:

//consultando pessoas pelo cnpj
        // GET: api/pessoas/888888888888
        [ResponseType(typeof(pessoa))]
        public IHttpActionResult Getpessoa_cnpj_cpf(int cnpj_cpf)
        {
            pessoa pessoa = db.pessoa.Find(cnpj_cpf);
            if (pessoa == null)
            {
                return NotFound();
            }

            return Ok(pessoa);
        }

How do I get api / cnpj / 8888888888 or any other path as long as it funcines?

    
asked by anonymous 30.06.2017 / 12:41

1 answer

2

You need to make the following changes:

- > Change the method parameter type to string

- > Add% Annotation ActionName to your Action, so you can call the method with localhost/pessoas/GetCNPJCPF/{valor_do_parametro}

- > Instead of using .Find , use .Where , and compare the data coming from your request with the column in your database table.

//consultando pessoas pelo cnpj
// GET: api/pessoas/888888888888
[ResponseType(typeof(pessoa))]
[ActionName("GetCNPJCPF")]
public IHttpActionResult Getpessoa_cnpj_cpf(string cnpj_cpf)
{
    pessoa pessoa = db.pessoa.Where(p => p.cnpj_cpf == cnpj_cpf).FirstOrDefault();
    if (pessoa == null)
    {
        return NotFound();
    }

    return Ok(pessoa);
}

For the comparison I made in .Where : If the field of CPF / CNPJ does not have the same name that I include here (in the case p.cnpj_cpf), just replace it with the name of the attribute of your class.

    
30.06.2017 / 13:57