How to return query by a string using Webapi?

Asked

Viewed 680 times

1

I have the following code that gives me an error:

The inline Constraint resolver of type 'Defaultinlineconstrainaintresolver' was Unable to resolve the following inline Constraint: 'String'.

Exception Details: System.Invalidoperationexception: The inline Constraint resolver of type 'Defaultinlineconstraintresolver' was Unable to resolve the following inline Constraint: 'String'.

        //http://localhost:1608/api/ApiCidade/consulta/clienteLoginSenha/
        [HttpGet]
        [Route("consulta/clienteLoginSenha/{email:long};{senha:long}")]
        public HttpResponseMessage ClientePorLoginSenha(string email, string senha)
        {
            try
            {
                var tCliente = new ClienteAplicacao();
                var listarDeClientes = tCliente.ListarPorLoginSenha(email,senha);
                return Request.CreateResponse(HttpStatusCode.OK, listarDeClientes.ToArray());
            }
            catch (Exception ex)
            {

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





//http://localhost:1608/api/ApiCidade/consulta/clientePorNome/e
[HttpGet]
[Route("consulta/clientePorNome/{nome:String}")]
public HttpResponseMessage ClientePorNome(string nome)
{
    try
    {
        var tCliente = new ClienteAplicacao();
        var listarDeClientes = tCliente.ListarPorNome(nome);
        return Request.CreateResponse(HttpStatusCode.OK, listarDeClientes.ToArray());
    }
    catch (Exception ex)
    {
        return Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message);
    }
}

consultation in the application :

        public List<Cliente> ListarPorNome(string nome)
        {
            var strQuery = string.Format("select * from clientes where nome like {0}", nome + '%');

            using (contexto = new Contexto())
            {
                var retornoDataReader = contexto.ExecutaComandoComRetorno(strQuery);
                return TransformaReaderEmListaObjetos(retornoDataReader);
            }

        }


     private List<Cliente> TransformaReaderEmListaObjetos(SqlDataReader reader)
        {
            var clientes = new List<Cliente>();
            while (reader.Read())
            {

                Cliente cliente = new Cliente()
                {
                    Id = reader["id"] == DBNull.Value ? 0 : Convert.ToInt32(reader["id"]),
                    Nome = reader["nome"] == DBNull.Value ? string.Empty : reader["nome"].ToString(),
                    DataNascimento = reader["data_nascimento"] == DBNull.Value ? DateTime.MinValue : Convert.ToDateTime(reader["data_nascimento"]),
                    Email = reader["email"] == DBNull.Value ? string.Empty : reader["email"].ToString()

                };

                clientes.Add(cliente);
            }
            reader.Close();
            return clientes;
        }
  • What kind of method Listarpornome (tCliente.Listarpornome(name);) returns? When I use, I return directly to the list (List<T>).

  • I added the most complete code, see if you can help me

  • I don’t think you need to convert to array (listDeClientes.Toarray()) because it is already a list. Already tried to return only the list?

  • my question is on this line:[Route("query/clientPorNome/{name:String}")] I cannot use this way.

1 answer

0


The :String is not a valid Constraint for route configuration. Below is the link of constraints allowed for route configuration. Check if without this Constraint your code continues to raise this error.

{ "bool", typeof(BoolRouteConstraint) },
{ "datetime", typeof(DateTimeRouteConstraint) },
{ "decimal", typeof(DecimalRouteConstraint) },
{ "double", typeof(DoubleRouteConstraint) },
{ "float", typeof(FloatRouteConstraint) },
{ "guid", typeof(GuidRouteConstraint) },
{ "int", typeof(IntRouteConstraint) },
{ "long", typeof(LongRouteConstraint) },

// Length constraints
{ "minlength", typeof(MinLengthRouteConstraint) },
{ "maxlength", typeof(MaxLengthRouteConstraint) },
{ "length", typeof(LengthRouteConstraint) },

// Min/Max value constraints
{ "min", typeof(MinRouteConstraint) },
{ "max", typeof(MaxRouteConstraint) },
{ "range", typeof(RangeRouteConstraint) },

// Regex-based constraints
{ "alpha", typeof(AlphaRouteConstraint) },
{ "regex", typeof(RegexRouteConstraint) }

You can use the AlphaRouteConstraint to restrict the parameter to contain only Latin alphabet letters A-Z, including upper and lower case letters.

Example:

[Route("consulta/clientePorNome/{nome:alpha}")]

Sources:

https://stackoverflow.com/questions/23412021/defaultinlinecontraintresolver-error-in-webapi-2

http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2#constraints

  • 1

    correct, the problem was this, after using the name:alpha went all right

  • Perfect. Comment if there is any need for clarification

  • When I need to send a route with 2 information : [Route("query/clientLoginSenha/{email:long};{password:long}")] how would you like? I thank you,

  • [Route("query/clientLoginSenha/{email:long}/{password:long}")], however, this is an answer to another question. I suggest to mark this as answered and create another one for this question. Make sure it doesn’t exist before to not create a duplicate question.

Browser other questions tagged

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