Return Notfound() Web Api c#

Asked

Viewed 1,019 times

0

I need that if the return of Get of controller below for null he returns a specific message, where he has return NotFound(), but it’s not working as expected and I tried to implement separately but always gives error.

[ResponseType(typeof(pessoa))]
[ActionName("GetCNPJCPF")]
public IHttpActionResult GetCNPJCPF(string cnpj_cpf)
{
     pessoa pessoa = db.pessoa.OfType<pessoa>()
                       .Where(p => p.cpf_cnpj == cnpj_cpf).FirstOrDefault();
     if (pessoa == null)
     {
         return NotFound();
     }
     return Ok(pessoa);
}

if it does not find simply from error HTTP 404

  • It already comes native when we create a Controller by Wizard! I tried to implement by https://stackoverflow.com/questions/20139621/how-do-i-return-notfound-ihttpactionresult-with-an-error-message-or-exception, but without success.

  • I don’t understand your problem. ApiController.NotFound creates a 404 response, which is what you return when pessoa is void.

  • @merchant , I need him to return a message , ex. No record found, because when I look for an ajax it appears as error because of page 404

3 answers

1


You can use this:

return Content(HttpStatusCode.BadRequest, "Qualquer objeto");

0

You can try the following:

return NotFound("Sua mensagem aqui");

Browser output "File not found ..."

0

You’ll have to create your custom message separately if you want it to return. Here explains how to do

Browser other questions tagged

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