Error searching for record with Firstordefaultasync ASP . NET CORE 3.0

Asked

Viewed 62 times

0

I have a method to search the client in the database by the number of the CPF (no points, only the numbers), but in the database the type is as VARCHAR.

I did some tests by POSTMAN to test the API route. When I put in the method I will send the parameter by SearchCliente([FromBody]string cpf) and send the POST with the CPF number by POSTMAN’s Body it returns the customer, but if I put in the method SearchCliente(string cpf) and send the number of the CPF it returns Notfound.

I also put a message to check the error, but I realized that it is not entering the IF condition.

Below the complete code of the method how it works:

        // GET: api/cliente/search/12345678901
        [HttpPost]
        [Route("search")]
        public async Task<ActionResult<Cliente>> SearchCliente([FromBody]string cpf)
        {
            var cliente = await _context.Clientes.FirstOrDefaultAsync(c => c.cpf == cpf);

            if (cliente == null)
            {
                return NotFound(new { message = "CPF não cadastrado!" });
            }

            return cliente;
        }

And the method code that doesn’t work:

        // GET: api/cliente/search/12345678901
        [HttpPost]
        [Route("search")]
        public async Task<ActionResult<Cliente>> SearchCliente(string cpf)
        {
            var cliente = await _context.Clientes.FirstOrDefaultAsync(c => c.cpf == cpf);

            if (cliente == null)
            {
                return NotFound(new { message = "CPF não cadastrado!" });
            }

            return cliente;
        }

Below some images of the tests in POSTMAN

inserir a descrição da imagem aqui

inserir a descrição da imagem aqui

inserir a descrição da imagem aqui

I’ve tried to convert to Tostring, but it didn’t solve either. Could someone tell me where I’m going wrong?

Thank you so much!

Typescript code that makes the POST:

import { Component, OnInit } from '@angular/core';
import { ClienteService } from '../services/cliente.service';
import { Router } from '@angular/router';
import { NgForm } from '@angular/forms';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-nav-menu',
  templateUrl: './nav-menu.component.html',
  styleUrls: ['./nav-menu.component.css']
})
export class NavMenuComponent implements OnInit {

  router: Router;

  constructor(public service: ClienteService, public http: HttpClient, router: Router) {
    this.router = router;
  }

  ngOnInit(): void {

  }

  cpf: string;
  readonly rootURL = "http://localhost:54038/api"

  onSearchCliente(form:NgForm){
    return this.http.post(this.rootURL + '/search', this.cpf).subscribe(
      res => {
        this.router.navigate(['', 'painel-cliente']);
      },
      err =>{
        console.log(err);
        this.router.navigate(['', 'acesso-negado']);
      }
    )
  }
}

inserir a descrição da imagem aqui

  • The problem is that you intend to pass the CPF in the URL instead of in the body?

  • No! I am sending via POST via that image input text above

  • And how is the payload being shipped there? You can see it in the tab network.

  • I put the payload image

1 answer

0

See, you’re firing a request like this:

this.http.post(this.rootURL + '/search', this.cpf)

A piece of the URL is missing:

this.http.post(this.rootURL + '/cliente/search', this.cpf)
  • Wow.. hadn’t even seen it! I changed here, now it gave error 415 (Unsupported Media Type)

  • There is another problem. I believe it is the case to open another question, otherwise this thread goes out of focus.

  • All right, I’ll check here. But thanks for now!

  • No. it was because it was like [Frombody]... I took it and keeps giving Notfound! Strange that it does not return the empty message!

  • @Rdamazio Not young, the [FromBody] informs that you will pass the parameters through the body of the request, if you take it is obvious that it will not work.

  • Got it.. I’m going to have to search here for bug 415

  • Check the payload that is going, must have some header stating the type of content

  • I think I noticed something checking the payload... It is only sending the number of the CPF without quotation marks with nothing. And in POSTMAN when it worked I sent with double quotes and the format was JSON. I wonder if this is it?

Show 4 more comments

Browser other questions tagged

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