I add a controller webapi
, the IDE takes care of generating the class WebApiConfig
and registering the configurations in it global.asax
, so far everything is perfect. I run my asp.net-mvc application I try to access one Action
of my own controller
and I get a 404 error.
As I had previously had routing problems (due to ignorance) I suppose that it is due to something similar.
My WebApiConfig
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Global.asax
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
GlobalConfiguration.Configure(WebApiConfig.Register);
}
Controller Webapi:GerenciasController
public IEnumerable<Gerencia> Get()
{
...
}
The most curious thing for me is that I have another one controller
that works, the difference is that in me get
I specify a different routing than the default one.
[Route("api/Legajo/{idCompania}/{idLocal}/{fecha}")]
public IEnumerable<Legajo> Get(short idCompania, short idLocal, string fecha)
{
...
}
I clarify that I am doing a httpget
:
$.getJSON('/api/Gerencias/', null, function (data) {
...
});
I also tried from my browser directly accessing the route:
http://misitio/api/Gerencias/
Remember that
Get()
you must invoke it using the correct http verb, it will only access it if you used aGET
del http.Using the
GET
as a verb and the urlhttp://{sitio}/api/nombreController
should workYou can use postman or fiddler to test the webapi.
Also try to define the attributes
I am commenting on this because of what I saw in this article.
Attribute Routing in ASP.NET Web API 2
Another way could be
Analyze in the article the title "Route Prefixes" there mentions what I comment. It is further in the controller defines the attribute
[RoutePrefix("api/books")]
I found the problem, it is the order of registering the routing configurations. It
IDE
automatically adds everything to the end for you (see my question), this causes the aforementioned malfunction.Try adding the action tag to the routerTemplate property , for example: