Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 }

        );
    }
}
like image 231
Agamemnon Avatar asked Mar 23 '26 15:03

Agamemnon


1 Answers

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() 
like image 85
Roman Marusyk Avatar answered Mar 26 '26 15:03

Roman Marusyk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!