Search code examples
asp.net-web-api2asp.net-web-api-routing

ASP. NET Web Api 2 issue - The requested resource does not support HTTP method 'GET'


I am not sure why I am getting a "404 Not Found" on the following GET call to my api (using PostMan)

http://localhost:53840/api/v1/MessageLog/SomeStuff/3

The method in the Controller is as follows

    [System.Web.Http.HttpGet]
    public string SomeStuff(int s)
    {            
        return "Received input !";            
    }  

The Register method in the WebApiConfig class has the only route as follows :

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

But when I change the code to

    [System.Web.Http.HttpGet]
    public string SomeStuff()
    {            
        return "Received input !";            
    }  

The call http://localhost:53840/api/v1/LogMessage/SomeStuff works and POSTMAN displays the "Recieved input !" string in the response body.

Is there a specific calling convention for passing in int/string etc. (I tried using a [FromUri] without much success) ? I have another POST method in the controlled which takes a JObject and that seems to be working perfectly fine.


Solution

  • It should be something like:

    [System.Web.Http.HttpGet]
    public string SomeStuff(int id)
    {            
        return "Received input !";            
    }
    

    Web API matches the parameter by name. In your route template, it is defined as {id} so the action parameter name must match that.

    The reason the second one works is because the id is optional and the action matches the template.