Reputation: 7069
I am working on an MVC 5 application. In that i have created an Area named Organization
. I have also created an (API) folder in controllers folder of that Area. So my structure have become like
/Areas/Organization/Controllers/API/OrganizationAPI
Where OrganizationAPI
is API Controller for Organization
Area. Now my problem is regarding Routing in MVC. I am unable to find what URL will invoke my API.
I have tried with this URL
http://localhost:80/Organization/API/OrganizationAPI/getData
where getData
is My action method. But it says resource not found. Can any please help me in understanding that how can i register my own routes so that i can map my actions with URLs and also suggest me some reference URL for URL Routing in MVC 4 or above.
Upvotes: 11
Views: 18389
Reputation: 2551
If your project already contains a WebApiConfig.cs file, great! You just need to add a route like below:
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 }
);
// NEW ROUTE FOR YOUR AREA
config.Routes.MapHttpRoute(
name: "API Area Default",
routeTemplate: "api/AREA/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Upvotes: 9
Reputation: 31
You can just create another route to emulate areas, but this won't work nicely with the "namespace" concept only: You will see that controllers in one area will be accessible from another areas. That´s because "AREA" is not really taken in count in Web API as MVC routing does.
Therefore, if you have controllers with the same name in different areas an exception will be thrown:
Multiple types were found that match the controller named ‘tickets’. This can happen if the route that services this request (‘api/{controller}/{id}’) found multiple controllers defined with the same name but differing namespaces, which is not supported. The request for ‘tickets’ has found the following matching controllers: .....
The solution for me was following this elegant workaround from Martin Devillers Blog:
http://blogs.infosupport.com/asp-net-mvc-4-rc-getting-webapi-and-areas-to-play-nicely/
SoFarSoGood!
Upvotes: 1
Reputation: 1492
The default routes created for API controllers doesn't take in consideration the method name (getData in your case), not like in regular controllers. It depends on the http method (get/post/put/delete) and the parameters you send, the action methods should start with same as the http method name (e.g. getData, will be called when get method is used).
you can add a custom route to call actions on api controller by name.
So to call your get data method, the url should look like: Area/API/Controller, don't add the method name.
Upvotes: 1