Correct method to write to WEB API?

Asked

Viewed 686 times

7

I did a test using a method this way, test using the Postman is worked, wondered if this way I might have any problem.

in the Controller

//http://localhost:1608/api/ApiGuiaCidade/cadastrar/cliente/jose/02-02-2015/[email protected]/124546
[HttpPost]
[Route("cadastrar/cliente/{nome}/{datanascimento}/{email}/{senha}")]
public HttpResponseMessage clienteCadastro(string nome,DateTime datanascimento,string email,string senha)
{
    try
    {
        var tCliente  = new ClienteAplicacao();
        tCliente.Inseri(nome,datanascimento,email,senha);
        return Request.CreateResponse(HttpStatusCode.OK, "Cadastro do cliente  " + nome + "  realizado.");
    }
    catch (Exception ex )
    {

        return Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message);
    }
}

in the application:

public void Inseri(string nome, DateTime datanascimento, string email, string senha)
{
    var strQuery = "";
    strQuery += "INSERT INTO CLIENTES (NOME, DATA_NASCIMENTO,EMAIL, SENHA)";
    strQuery += string.Format(" VALUES ('{0}','{1}','{2}','{3}' )", nome, datanascimento, email, senha);

    using (contexto = new Contexto())
    {
        contexto.ExecutaComando(strQuery);
    }
}
  • I use it like this too.

  • By chance you are using Entity Framework?

  • 1

    I don’t think this is the best practice, imagine the size of the url when you pass 50 or more fields as parameter. I also think that you do not want to pass password as plain text. The correct is to pass the values by JSON, XML, etc and then deserialize .

  • @Randrade I am not using Entity Framework

  • I think you can do SQL Injection with this code, another point, method name as far as I know, are action verbs... in your case it would be INSERT and not INSERT... but it’s just a small detail.

  • @Paulohdsousa , I made the name change to INSERT, you’re right about SQL Injection, but the person would have to know the exact path to it, how I’m going to use for mobile so I think it gets more complicated

  • You cannot send a JSON or XML like @rubStackOverflow said?

Show 2 more comments

1 answer

1

Come on,

When you have a request to persist, you should take some precautions and adopt some good practices to avoid any problems. In the case of a requisition POST To persist something, you can very well send the data in the body of the request, which exists precisely for this. On the Asp.net web api side, you can create a class that makes the binding of this data and delivered an object ready for you to work, for example.

public class ClienteDto
{
    public string Nome { get; set; },

    public DateTime DataNascimento { get; set; }

    public string Email { get; set; }

    public string Senha { get; set; }
}

In your API method, you could receive an object of this type.

[HttpPost]
[Route("cadastrar/cliente")]
public HttpResponseMessage clienteCadastro(ClientDto clienteDto)
{
    // passe o objeto DTO para a cada de negócios...

    return Request.CreateResponse(HttpStatusCode.OK);  
}

Remember that when doing this, you must pass the data in the Body Request of your request, and this could be done using the format json, for example:

{
   Nome: "João",
   DataNascimento: "2000-01-05",
   Email: "[email protected]",
   Senha: "123456"
}

Note: If you can encrypt the password to traffic this in your request, is a safety recommendation.

Getting to the layer that will persist, I noticed that in your code ,you use ADO.Net. There is no problem in this, however, be careful what some colleagues have commented on in their question, about SQL Injection. Depending on how you build an instance of IDbCommand and adds parameters, you run the risk of having an unwanted command running in your database. You could try something like this:

public void Inserir(ClientDto clienteDto)
{
    var strQuery = "@"INSERT INTO CLIENTES (NOME, DATA_NASCIMENTO,EMAIL, SENHA) VALUES (@nome, @datanascimento, @email, @senha)"

    using (var conexao = new Conexao())
    {
            var parametros = List<SqlParameter>();

            var nomeParametro = new SqlParameter("@nome", SqlDbType.VarChar);
            nomeParametro.Value = clienteDto.Nome;

            parametros.Add(nomeParametro)

            // adicione outros parametros nesta lista


            // implement uma sobrecarga que adicione os parametros ao seu Command neste método!
            contexto.ExecutaComando(strQuery, parametros);
    }   
}

I hope it helps.

Browser other questions tagged

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