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.
It routes an incoming HTTP request to a particular action method on a Web API controller. Web API supports two types of routing: In the convention-based routing, Web API uses route templates to determine which controller and action method to execute.
MVC 5 supports a new type of routing, called attribute routing. As the name implies, attribute routing uses attributes to define routes. Attribute routing gives you more control over the URIs in your web application. The earlier style of routing, called convention-based routing, is still fully supported.
Then, it matches the request in the route table to ensure which controller and which action will be processed. Basically, Route is an approach which defines URL pattern and handles the information. In MVC, routes decide which Controller method to be executed on a particular request. An MVC URL consists of the following properties.
For example, request url is http://localhost:1234/api/myschool is matched with School route template, so it will be handled by SchoolController. Note: The reason to use api in the route template is just to avoid confusion between MVC controller and Web API controller. You can use any pattern based on your app architecture.
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 }
);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With