Path to the Webapi URL

Asked

Viewed 598 times

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?

  • 1

    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 type int.

  • @Anacarolinamanzan , errei put as int but in the bank is string, I changed to Getpessoa_cnpj_cpf(string cnpj_cpf)

  • @Ricardopontual , defined a second route as follows: config.Routes.MapHttpRoute(
 name: "DefaultApiWithAction",
 routeTemplate: "api/{controller}/{action}/{cpf_cnpj}",
 defaults: new { cpf_cnpj = RouteParameter.Optional }

  • 1

    @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?

  • @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",

  • 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.

  • @Anacarolinamanzan, yes I am using Entity framework with codefirst. thank you I am very grateful.

  • 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 field int for the cnpj, will give overflow or truncate the numbers. Finally, your route can even accept the parameter as string, but you need to convert in time to get the data using the Entity Framework.

Show 4 more comments

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 make the call of the method through localhost/pessoas/GetCNPJCPF/{valor_do_parametro}

-> Instead of using .Find, use the .Where, and compare the data coming from your request with the column present 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 on .Where: if the CPF/CNPJ field does not have the same name as I include here (in the case p.cnpj_cpf), just replace it with the attribute name of your class.

  • apparently worked, but returned the message: "Não foram encontrados recursos HTTP que correspondam ao URI de solicitação 'http://localhost/api/pessoas/GetCNPJCPF/10999558000186'.", I think there must be some problem in my route, I defined the same in Webapiconfig.

  • config.Routes.MapHttpRoute(
 name: "DefaultApiWithAction",
 routeTemplate: "api/{controller}/{action}/{cnpj_cpf}",
 defaults: new { cpf_cnpj = RouteParameter.Optional });

  • If you want to call the action that way, you can resolve by adding an Annotation above the action so: [ActionName("GetCNPJCPF")]. What happens is that the default of the Webapi is to call api/controller/action/{parametros}. To make the call in this case, I believe the action name Annotation already solves.

  • Ah! Keep that route you created, ok?

  • 1

    worked. Thanks, saved my morning!

Browser other questions tagged

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