Web Api ASP.NET can not find the method

2

By consuming the API created in asp.net with postman I get the following error

{"Message": "No se ha encontrado ningún recurso HTTP que coincida con la URI de la solicitud 'http://localhost:9401/api/Usuarios/Login'.",
"MessageDetail": "No se encontró ninguna acción en el controlador 'Usuarios' que coincida con la solicitud."}

Here is a capture of the postman at the time of the query

Here is the code of the method I did in the api controller

[HttpPost]
[ActionName("Login")]
public IHttpActionResult Login(string correo, string password)
{
    Hashtable Respuesta = new Hashtable();
    UsuariosBL Usuario = new UsuariosBL()
    {
        Email = correo,
        Password = password
    };
    UsuariosBL UsuarioResultado = Usuarios.Login(Usuario);
    if(UsuarioResultado.IDUsuario > 0)
    {
        Respuesta.Add("success", true);
        Respuesta.Add("usuario", UsuarioResultado);
        return Ok(Respuesta);
    }
    else
    {
        Respuesta.Add("success", false);
        Respuesta.Add("error", "El usuario o la contraseña son incorrectos");
        return Ok(Respuesta);
    }
}
    
asked by Daniel Pat 22.08.2018 в 22:28
source

2 answers

2

To access the actions of the controller, it depends a lot on the configuration of the routes. The default generation is as follows in the file App_start\WebApiConfig.cs :

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

Given this configuration, just replace {controller} , by the name of your controller and {action} by the name of your action. In your question you do not mention the name of the controller but given the screenshot of Postman, it should be Usuarios and your action is called Login , leaving the url:

http://localhost:9401/api/Usuarios/Login

If you still have the same problem, you can declare a static route to access the action using the Route attribute. The definition of the action should be as follows:

[HttpPost]
[Route("Usuarios/Login")]
public IHttpActionResult Login(string correo, string password)
{
    // Código
}

If you want to know more about the functioning of the routing, here is the link to the official documentation .

Update:

I have noticed a topic in the submission of your request and in the definition of your API. When you expect parameters directly in the action (in this case correo and password ) the functioning of the Web API interprets that it expects it directly from the URL, that is to say http://localhost:9401/api/Usuarios/[email protected]&password=MiPassword , that's why if you send it by GET you it's going to work.

The solution consists of creating a model to use directly in the action, and in this way the API has the possibility to read the body of the request and to deserialize it to an object.

Model:

public class LoginRequest
{
    public string Correo { get; set; }
    public string Password { get; set; }
}

Code of action:

[HttpPost]
[Route("Usuarios/Login")]
public IHttpActionResult Login(LoginRequest loginRequest)
{
    // Código
}

Request data:

  • URL: http://localhost:9401/api/Usuarios/Login
  • Method: POST
  • Headers:
    • Content-Type: Application / json
  • Body of the request (Body):

    {
        "Correo" : "[email protected]",
        "Password" : "MiPassword"
    }
    
answered by 22.08.2018 / 23:10
source
0

Set the [FromBody] attribute in the definition of your method. As you have already been told, create a model

public class LoginRequest
{
    public string Correo { get; set; }
    public string Password { get; set; }
}    
public IHttpActionResult Login([FromBody] LoginRequest request)

By default, the Web API tries to get the simple types from the request URI. The FromBody attribute tells the Web API to read the value from the request body.

[HttpPost]
[ActionName("Login")]
public IHttpActionResult Login([FromBody] LoginRequest request)
{
    var correo = request.Correo;
    var password = request.Password;
    Hashtable Respuesta = new Hashtable();
    UsuariosBL Usuario = new UsuariosBL()
    {
        Email = correo,
        Password = password
    };
    UsuariosBL UsuarioResultado = Usuarios.Login(Usuario);
    if(UsuarioResultado.IDUsuario > 0)
    {
        Respuesta.Add("success", true);
        Respuesta.Add("usuario", UsuarioResultado);
        return Ok(Respuesta);
    }
    else
    {
        Respuesta.Add("success", false);
        Respuesta.Add("error", "El usuario o la contraseña son incorrectos");
        return Ok(Respuesta);
    }
}

I also add the following possibility to code the API

[HttpPost]
[ActionName("Login")]
public IHttpActionResult Login(FormDataCollection form)
{
    var correo = form.Get("correo");
    var password = form.Get("password");

    Hashtable Respuesta = new Hashtable();
    UsuariosBL Usuario = new UsuariosBL()
    {
        Email = correo,
        Password = password
    };
    UsuariosBL UsuarioResultado = Usuarios.Login(Usuario);
    if(UsuarioResultado.IDUsuario > 0)
    {
        Respuesta.Add("success", true);
        Respuesta.Add("usuario", UsuarioResultado);
        return Ok(Respuesta);
    }
    else
    {
        Respuesta.Add("success", false);
        Respuesta.Add("error", "El usuario o la contraseña son incorrectos");
        return Ok(Respuesta);
    }
}
    
answered by 23.08.2018 в 09:16