Httpget parameter not detected

Asked

Viewed 242 times

0

Good afternoon guys, I don’t know why my parameter is not recognized, can you help me? The value does not arrive in c# but this present in the angle c#

[HttpGet]
[Route("carregarUsuarioPorId")]
public HttpResponseMessage BuscarUsuarioPorId()
{
        try
        {
            WSS_RetornoListaDTO<Usuario> wss = new WSS_RetornoListaDTO<Usuario>();

            int idUser = 0;

            var req = Request.GetQueryNameValuePairs();

            if (req != null)
            {
                foreach (var parameter in req)
                {
                    if (parameter.Key.Equals("id"))
                        idUser = int.Parse(parameter.Value.ToString());
                }
            }

            usuarioDAO = new UsuarioDAO();
            wss.resultado = usuarioDAO.BuscarUsuarioPorId(idUser);
            if (wss.resultado.Count > 0)
            {
                wss.codRetorno = 200;
                wss.msgRetorno = "Sucesso";

                return Request.CreateResponse<WSS_RetornoListaDTO<Usuario>>(HttpStatusCode.OK, wss);
            }
            else
                return Request.CreateResponse(HttpStatusCode.NoContent, "Usuario não localizado");
        }
        catch (Exception e)
        {
            return Request.CreateResponse(HttpStatusCode.BadRequest, "ERRO - " + e.Message);
        }
}

parameter call:

getUserPorId: function (idUser) {
    var id = [];
    id[0] = idUser;
    return 
    $http.get('http://localhost:61223/usuario/carregarUsuarioPorId',id)
      .then(function (response) {
        return response.data;
      });
  },

2 answers

3


On the call

public HttpResponseMessage BuscarUsuarioPorId()

there is no parameter. The api will not recognize, because probably your Routeconfig is saying id is optional. Put this way

public HttpResponseMessage BuscarUsuarioPorId(int id)

and you will save all this Boilerplate code

var req = Request.GetQueryNameValuePairs();

if (req != null)
{
    foreach (var parameter in req)
    {
        if (parameter.Key.Equals("id"))
            idUser = int.Parse(parameter.Value.ToString());
    }
}
  • 1

    Just complementing, it is always interesting to put the parameter on the route as well: [Route("carregarUsuarioPorId/{id:int:min(1)}")] so I can restrict with Constraint what is my value in the URL.

1

To pass parameters on query of $http#get you must pass the object config as the second parameter:

var params = {};

params.id = id;

$http.get('http://localhost:61223/usuario/carregarUsuarioPorId', {params: params}).then(function(response) {
  return response.data;
});

Browser other questions tagged

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