Get the return of a Webapi method?

Asked

Viewed 541 times

-3

I have the following code is I want to get a return on the result variable if it is true or false, how could I do it?

//http://localhost:1608/api/ApiCidade/deletar/cliente/10
[HttpDelete]
[Route("deletar/cliente/{id:int}")]
public HttpResponseMessage ClienteDeletar(int id)
{
    try
    {
        var resultado = true;
        var tCliente = new ClienteAplicacao();
        tCliente.Excluir(id);
        return Request.CreateResponse(HttpStatusCode.OK, resultado);
    }
    catch (Exception ex)
    {
        return Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message);
    }
}

In the App I have:

public void Excluir(int id)
{
    var strQuery = string.Format("DELETE FROM clientes WHERE id= {0}", id);
    using (contexto = new Contexto())
    {
        contexto.ExecutaComando(strQuery);                  
    }
}
  • I don’t understand what you want.

  • 1

    this duplicate [ http://answall.com/questions/96643/howto returnr-consulta-por-uma-string-usando-webapi]

  • [http://answall.com/questions/96643/como-retornar-consulta-por-uma-string-usando-webapi]

  • And what would be the criteria for true or false? Return from where?

1 answer

1


From what I’ve seen, you’re using that model to develop your API.

You have to return true or false in the delete method, for this I made some modifications to your code, take a look at:

public bool Excluir(int id)
{
    var retorno = 0;
    var strQuery = string.Format("DELETE FROM clientes WHERE id= {0}; SELECT id FROM clientes WHERE id = {0}", id);
    using (contexto = new Contexto())
    {
        var reader = contexto.ExecutaComandoComRetorno(strQuery);
        while (reader.Read()) {
            retorno = Convert.ToInt32(reader["id"]);
        }
        reader.Close();
    }

    if (retorno == 0)
        return true;
    return false;
}

And in your API, you will store the return value:

[HttpDelete]
[Route("deletar/cliente/{id:int}")]
public HttpResponseMessage ClienteDeletar(int id)
{
    try
    {
        var tCliente = new ClienteAplicacao();
        var resultado = tCliente.Excluir(id);
        return Request.CreateResponse(HttpStatusCode.OK, resultado);
    }
    catch (Exception ex)
    {
        return Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message);
    }
}

The idea would be to check if the registration with this id exists right after deletion. I didn’t test the example, but the idea would be something like this.

  • That’s right, that’s just what I needed!! I appreciate it!

Browser other questions tagged

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