Catch the return of a WebAPI method? [closed]

-3

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

//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 Application 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);                  
    }
}
    
asked by anonymous 06.11.2015 / 02:50

1 answer

1

From what I've seen, you're using this template to develop your API.

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

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 verify that the record with this id exists soon after the deletion. I did not test the example, but the idea would be something like this.

    
06.11.2015 / 12:39