简体   繁体   中英

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

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

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"; 
    }
}

Notice you are using both attribute routing on the controller/action and convention routing with config.Routes.MapHttpRoute.

config.Routes.MapHttpRoute will map the routes as per your definition " api/{controller}/{id} ".

While attribute routing, will map the routes based on how you've defined them: /login/authenticate .

Also, since you are using both attribute routing and convention routing, attribute routing takes presendence. I would stick to using one or the other. Having both adds a bit of confusion as to what route will be used to access an action method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM