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

WebAPI controller not working while another one does


I have an API that works fine locally and when I move it to the live environment it doesn't.

The main POST action on the affected controller returns:

NotFound

With a test GET action I get back:

"Message": "No HTTP resource was found that matches the request URI

Strangely, when I uploaded a testController with the same test action as used in the main controller I get a proper response from the API.

This is the test that works fine:

public class TestController : ApiController
{

    [AllowAnonymous]
    [HttpGet]
    public HttpResponseMessage helloWorld()
    {
        return Request.CreateResponse(HttpStatusCode.OK, "HelloWorld!");
    }
}

The controller which does not work:

public class DeviceController : ApiController
{

    [AllowAnonymous]
    [HttpGet]
    public HttpResponseMessage helloWorld() // This returns: "No HTTP resource was found that matches the request URI 'http://api.mySite.com/api/Device/helloWorld'."
    {
        return Request.CreateResponse(HttpStatusCode.OK, "HelloWorld!");
    }

    [AllowAnonymous]
    [HttpPost]
    public HttpResponseMessage Login([FromBody] LoginObject loginObject) // This returns: "NotFound"
    {
        ...
    }

}

Here is the web config:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(

            name: "API Default",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }

        );
    }
}

Solution

  • Try to add explicitly declare of route like by acrion

    [Route("api/Device/helloWorld")]
    [AllowAnonymous]
    [HttpGet]
    public HttpResponseMessage helloWorld() 
    

    or

    [RoutePrefix("api/Device")]
    public class DeviceController : ApiController
    

    and then

    [Route("helloWorld")]
    [AllowAnonymous]
    [HttpGet]
    public HttpResponseMessage helloWorld()