Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Web API Route Controller Not Found

I am trying to post to the following Web API:

http://localhost:8543/api/login/authenticate

LoginApi (Web API) is defined below:

[RoutePrefix("login")]
public class LoginApi : ApiController
{
    [HttpPost]
    [Route("authenticate")]
    public string Authenticate(LoginViewModel loginViewModel)
    {  
        return "Hello World"; 
    }
}

WebApiConfig.cs:

public static void Register(HttpConfiguration config)
{
    // Web API configuration and services

    // Web API routes
    config.MapHttpAttributeRoutes();

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

Here is the error I get:

Request URL:http://localhost:8543/api/login/authenticate
Request Method:POST
Status Code:404 Not Found
Remote Address:[::1]:8543
like image 422
john doe Avatar asked Jul 21 '26 02:07

john doe


2 Answers

Your controller name "LoginApi" needs to end in "Controller" in order for the framework to find it. For example: "LoginController"

Here is a good article which explains routing in ASP.NET Web API: http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api

like image 160
thiag0 Avatar answered Jul 23 '26 16:07

thiag0


You are using login as your route prefix on your controller so trying to call

http://localhost:8543/api/login/authenticate

will not be found as this code

[RoutePrefix("login")]
public class LoginApi : ApiController
{
    //eg:POST login/authenticate.
    [HttpPost]
    [Route("authenticate")]
    public string Authenticate(LoginViewModel loginViewModel)
    {  
        return "Hello World"; 
    }
}

will only work for

http://localhost:8543/login/authenticate

You need to change your route prefix to

[RoutePrefix("api/login")]
public class LoginApi : ApiController
{
    //eg:POST api/login/authenticate.
    [HttpPost]
    [Route("authenticate")]
    public string Authenticate(LoginViewModel loginViewModel)
    {  
        return "Hello World"; 
    }
}
like image 39
Nkosi Avatar answered Jul 23 '26 15:07

Nkosi