Friday, 19 September 2014

Using a WEB API Controller in an MVC Web Application project

Sometimes you may have a valid reason of hosting a Web API controller inside your MVC Web application. Usually when exposing REST services you are better of having your WEB API controllers encapsulated into a project of its own so you options of hosting them are broader.

However, if you must host a Web API controller inside your MVC application you can follow the steps below.

Environment wise, these instructions have been implemented and tested using MVC 5, Web Api 5.2 and VS 2013 (aka 'Tool for Men')

1.  Add a Web API controller to your existent MVC project.




2.  Set up the route configuration for WEB API controller.

When you create a MVC web application using the MVC template, Visual Studio will create
the RouteConfig class for you and implement the default MVC routing, as below:

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

In this class you can add new routes to your MVC application.

However, for matching REST requests to  a WEB API controller actions another routing is needed.

To implement the Web API routing just:

  1. Create a class on the App_Start folder of your MVC Web Application.
    If you create the class using the Visual Studio Wizard (i.e. CTR + Shift , A), remove the
    "App_Start" from the namespace of the class. By default Visual Studio will append the
    name of the folder "App_Start" to the namespace.
  2. Create a public static method named Register. This method is akin to the
    RegisterRouter method of the RouteConfig.cs

    public static void Register(HttpConfiguration config)
            {
                
    // Web API configuration and services
                
    // Web API routes
                config
    .MapHttpAttributeRoutes();
     
                config
    .Routes.MapHttpRoute(
                    name: 
    "DefaultApi",
                    routeTemplate: 
    "api/{controller}/{id}",
                    defaults: 
    new { id = RouteParameter.Optional }
                );

    You can add more routes to match the REST requests to the desired URI format.

    3. Add a references to the System.Web.Http.WebHost dll in your MVC Web Application.

    4. Add a  reference to the System.Web.Http namespace on the MVCApplication class
    (Global.asax.cs source file)

    5. On the Application_Start() method of the MVC Application class add this statement
    that will invoke the WebApiConfig.Register method

    GlobalConfiguration.Configure(WebApiConfig.Register); 
    

Now you should be able to invoke the methods in your Web API controller through REST verbs such as:
  /api/Students -> (get all students)
  /api/students/5 (get student with an id of 5)