Gerardo
Gerardo

Reputation: 369

Problems when Routing Api

I have RoutePrefix above in my controller like:

[RoutePrefix("api/Catalogos")]

And I have method like:

[System.Web.Http.AllowAnonymous]
[System.Web.Http.HttpGet]
public HttpResponseMessage Get(HttpRequestMessage request)
{
     //some code there
}

So when I use postman and send route like:

http://localhost:55720/api/Catalogos/

It runs without problems. The issue starts when I try to do another method like:

[System.Web.Http.AllowAnonymous]
[System.Web.Http.HttpGet]
[Route("GetCatalogo")]
public HttpResponseMessage GetCatalogoPadre(HttpRequestMessage request, string catalogo)
{
      //some code there
}

So I try in postman url like:

http://localhost:55720/api/Catalogos/GetCatalogo/

But I get:

{ "Message": "No HTTP resource was found that matches the request URI 'http://localhost:55720/api/Catalogos/GetCatalogo/'.",
"MessageDetail": "No action was found on the controller 'Catalogos' that matches the name 'GetCatalogo'." }

Why I can´t route it? I don´t understand what is wrong there.

Upvotes: 1

Views: 82

Answers (1)

Nkosi
Nkosi

Reputation: 246998

That is because it is most likely that you are routing via convention.

Make sure that attribute routing is enabled.

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

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

And in your controller make sure that the routes have been properly configured.

[RoutePrefix("api/Catalogos")]
public class CatalogosController : ApiController {

    [System.Web.Http.AllowAnonymous]
    [System.Web.Http.HttpGet]
    [Route("")] //Matches GET api/Catalogos
    public HttpResponseMessage Get() {
         HttpRequestMessage request = this.Request;
         //some code there
    }

    [System.Web.Http.AllowAnonymous]
    [System.Web.Http.HttpGet]
    [Route("GetCatalogo")] //Matches GET api/Catalogos/GetCatalogo
    public HttpResponseMessage GetCatalogoPadre(string catalogo) {
          HttpRequestMessage request = this.Request;
          //some code there
    }

}

Reference Attribute Routing in ASP.NET Web API 2

Upvotes: 0

Related Questions