ASP.NET MVC5 Routing with WEB Api2 & Area

In this article we will get explained how to map Web Api2 with Area. We will step into:

  1. Routing with WEB Api2 & Area
  2. Attribute Routing
  3. Parameters with Api2 Methods

Let’s get started: Routing with WEB Api2 & Area

First of all, we need to create a new MVC and Api Project with Visual Studio 2015.

Fig: 1.0

api_1

Fig: 1.1

api_2

Next we need to create an area in our project like below.

Fig:1.2

api_3

Now we will configure and add some controllers to our area. We also need to changes route in our Area Registration.

The main route(RouteConfig & WebApiConfig) will remain as it is.

Default Area Route: Below is the code sample of our Area registration.

public class AdminPanelAreaRegistration : AreaRegistration 
{
    public override string AreaName 
    {
        get 
        {
            return "AdminPanel";
        }
    }

    public override void RegisterArea(AreaRegistrationContext context) 
    {
        context.MapRoute(
            "AdminPanel_default",
            "AdminPanel/{controller}/{action}/{id}",
            new { action = "Index", id = UrlParameter.Optional }
        );
    }
}

Let’s create a Api2 empty Controller and create a method to invoke. Below is a image showing how to add an api2 Controller.

Fig:1.3

api_4

Method in api2 Controller.Let’s see what happened after build & run our application.

// GET: AdminPanel/api/Dashboard/
[HttpGet]
public string Get()
{
    string result = string.Empty;
    try
    {
        result = "We are in Dashboard From API2";
    }
    catch (Exception e)
    {
        e.ToString();
    }
    return result;
}

Output: This is showing that unable to locate the url content.

GET: AdminPanel/api/Dashboard/

api_5

Routing with WEB Api2 & Area: Let’s modify our existing Area route.

public class AdminPanelAreaRegistration : AreaRegistration
{
    public override string AreaName
    {
        get
        {
            return "AdminPanel";
        }
    }

    public override void RegisterArea(AreaRegistrationContext context)
    {
        //****************=======Default Api Route=========*******************
        context.Routes.MapHttpRoute(
                name: "AdminPanelApiAction",
                routeTemplate: "AdminPanel/api/{controller}/{action}"
            );

        context.Routes.MapHttpRoute(
                name: "AdminPanelApi",
                routeTemplate: "AdminPanel/api/{controller}"
            );

        //****************=======Default Route=========*******************
        context.MapRoute(
            "AdminPanel_dashboard",
            "AdminPanel/{controller}/{action}/{id}",
            new { Controller = "Dashboard", action = "Index", id = UrlParameter.Optional }
        );

        context.MapRoute(
            "AdminPanel_default",
            "AdminPanel/{controller}/{action}/{id}",
            new { action = "Index", id = UrlParameter.Optional }
        );
    }
}

Let’s put a break point in our apiController get method after that again build & run the application, put the previous URL and press enter.

Fig:1.4

api_6

This time it  hits the debug point like below image.

Output: 

api_7

Next we will focus how to use Attribute Routing.

Register Attribute Routing:

routes.MapMvcAttributeRoutes();

Finally Main route config

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.MapMvcAttributeRoutes(); 
        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

Let’s add another method with attribute [Route(“AdminPanel/api/Dashboard/Get/{id:int}”)]

//GET: AdminPanel/api/Dashboard/Get/1
[Route("AdminPanel/api/Dashboard/Get/{id:int}")]
[HttpGet]
public string Get(int? id)
{
    string result = string.Empty;
    try
    {
        result = "We are in Member - " + id + " From API2";
    }
    catch (Exception e)
    {
        e.ToString();
    }
    return result;
}

Let’s put a break point in our apiController get method after that again build & run the application, put the previous URL and press enter.

Fig:1.5

api_8

Output: 

api_9

 

Source Code: I’ve uploaded the full source code to download/clone , Hope this will help 🙂

Author:

Since March 2011, have 8+ years of professional experience on software development, currently working as Senior Software Engineer at s3 Innovate Pte Ltd.

4 thoughts on “ASP.NET MVC5 Routing with WEB Api2 & Area”

  • i tried but Not working with Web Api please check the error message following :

    An error has occurred.

    Multiple types were found that match the controller named ‘test’. This can happen if the route that services this request (‘JIB/api/{controller}/{action}’) found multiple controllers defined with the same name but differing namespaces, which is not supported. The request for ‘test’ has found the following matching controllers: WebApplication2.Areas.JIB.Controllers.TestController WebApplication2.Areas.JCB.Controllers.TestController

    System.InvalidOperationException

    at System.Web.Http.Dispatcher.DefaultHttpControllerSelector.SelectController(HttpRequestMessage request) at System.Web.Http.Dispatcher.HttpControllerDispatcher.d__1.MoveNext()

Leave a Reply