Search code examples
asp.net-web-api2asp.net-mvc-routingurl-routing

Unable to call WebApi 2 method


I've added a webapi 2 controller to my project, inside api > LoginAPi as shown here:

enter image description here

Inside LoginApi I have the following:

[RoutePrefix("api/LoginApi")]
public class LoginApi : ApiController
{
    // GET api/<controller>/5
    public string Get(int id)
    {
        return "value";
    }

}

Inside my global.asax file I have:

public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        GlobalConfiguration.Configure(WebApiConfig.Register);
    }
}

Inside App_Start I have the following:

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

I then put a break point inside the Get method within LoginAPI and run the project and type the following into the URL:

http://localhost:37495/api/LoginApi/4

But I get : No HTTP resource was found that matches the request URI 'http://localhost:37495/api/LoginApi/4'.

So I thought OK let me specify the method name as so

http://localhost:37495/api/LoginApi/Get/4

This returns: The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.

Now I've been looking at this for a while so maybe I've missed something obvious, but if someone can please tell me what I'm doing wrong I'd very much appreciate it.


Solution

  • The routeTemplate you have set up would work for convention-based routing except for the fact that Web API adds the string "Controller" when searching for the controller class (as per this article). You therefore need to rename your controller class LoginApiController in order for the convention-based routing to work.

    For attribute-based routing, the addition of the RoutePrefix attribute should be combined with a Route attribute on your action. Try adding the following to your Get method in your controller:

    [HttpGet]
    [Route("{id}")]
    

    And then navigate to http://localhost:37495/api/LoginApi/4.