1
I have a Webapi Rest service, I managed the controllers by the wizard that defined the answers in "api/{controller}/{id}", such as 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 people cnpj tried to do so only that 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 works?
CPF/CNPJ information is being recorded in your bank as int?
– Ana Carolina Manzan
Did you add a specific route for this method? Something like
[Route("{api/pessoas/cnpj/{cnpj_cpf}")]
? A detail: the cnpj has 14 digits, will overflow with the typeint
.– Ricardo Pontual
@Anacarolinamanzan , errei put as int but in the bank is string, I changed to Getpessoa_cnpj_cpf(string cnpj_cpf)
– Gleyson Silva
@Ricardopontual , defined a second route as follows:
config.Routes.MapHttpRoute(
 name: "DefaultApiWithAction",
 routeTemplate: "api/{controller}/{action}/{cpf_cnpj}",
 defaults: new { cpf_cnpj = RouteParameter.Optional }
– Gleyson Silva
@Exact Intelidersistemas. As Ricardo said, as the CNPJ has 14 digits, if you keep this as int it will overflow. It worked by changing to string?
– Ana Carolina Manzan
@Anacarolinamanzan , changing to string gave another error
"ExceptionMessage": "The type of one of the primary key values did not match the type defined in the entity. See inner exception for details.\r\nNome do parâmetro: keyValues",
– Gleyson Silva
You’re using Entity Framework, right? This error is happening by the following... When you use the
.Find
with Entity, it attempts to fetch the data by the primary key of its table, which in this case I believe is an int. You will have to pass another instruction to be able to search for the CPF/ CNPJ. One minute and I already pass you how to do.– Ana Carolina Manzan
@Anacarolinamanzan, yes I am using Entity framework with codefirst. thank you I am very grateful.
– Gleyson Silva
There are several things... first, you can add the route itself
controller
, do not need to go in configuration.. second, if your table has a fieldint
for the cnpj, will give overflow or truncate the numbers. Finally, your route can even accept the parameter asstring
, but you need to convert in time to get the data using theEntity Framework
.– Ricardo Pontual