Getting Started With ASP.Net Web API 2 : Day 5

Introduction

In this article we will learn how to link a MVC Controller to an API Controller. As we have seen in previous articles this article describes the basic procedure of the Web API. This is the fifth article of mine explaing the Web API 2, the four (4) previous articles are:

In this article we will create a link to the controller. The controller uses an instance of System.web.Http.Routing.UrlHelper. This link also uses the base ApiController (as the URL property) and request context attached to an instance of HttpRequestMessage. To get the value , we are clicking the link button as the desired link or route method and passing the name of the MVC route and route default. 

  1. public class RouteConfig  
  2.    {  
  3.        public static void RegisterRoutes(RouteCollection routes)  
  4.        {  
  5.            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
  6.   
  7.            routes.MapRoute(  
  8.                name: "Home",  
  9.                url: "{controller}/{action}/{id}",  
  10.                defaults: new { controller = "Home", action = "Details", id = UrlParameter.Optional }  
  11.            );  
  12.        }  
  13.    }  
On the other hand, the MVC Controller side, System.Web.Mvc.UrlHelper is attached with the base MVC base controller class and that is able to generate Web API links Via the HttpRouteUrl method. In this article I have used a sample example of student, where I want to show a sample Book model, an in-memory representation of a repository of books and the API/MVC routing configuration. It is good to use the same model for both MVC and Web API endpoints as well as the cross-linking between Web API and MVC controllers. 

Prerequisites

There are the following things we need to use when developing a Web API 2 application under the Web Form.

  • Visual Studio 2013
  • ASP.NET Web API 2
Getting Started

In this section we will follow some sections and these are:
  • Create ASP.NET Web API With MVC
  • Add Web API 2 Controller
Create ASP.NET Web API with MVC

There are some basic procedures to follow, when creating a Web API along with MVC using Visual Studio 2013, we need to also check the Web API button, as we are showing in the following images.

Step 1

Open the Visual Studio 2013 and click New Project.

Step 2

Select the ASP.NET Web Application and provide a nice name for the project.

NewProject

Step 3

Select the Web API template and click the OK button.

SelectTemplate

Step 4

Add a Student class to the model where we define all the necessary fields. In the following image, I have defined some fields like Id, name, Address and College Name. 
  1. public class Student  
  2.     {  
  3.         public int Id { getset; }  
  4.         public string Name { getset; }  
  5.         public string Address { getset; }  
  6.         public string CollegeName { getset; }  
  7.         public string Link { getset; }  
  8.     }  
 Step 5

Add another Students class to the model where we field some dummy data inside into as in List.

  1. public class Students  
  2.     {  
  3.         public static List<Student> List = new List<Student>  
  4.        {  
  5.             new Student{ Id=101, Name="Rajeev Ranjan", CollegeName="MIT Pune", Address="New Delhi"},  
  6.           new Student{ Id=102, Name="Ashwani Gupta", CollegeName="D Y Patil College of Engineering Pune", Address="Hazaribagh"},  
  7.           new Student{ Id=103, Name="Nimit Joshi", CollegeName="Bhartiya Vidypeeth Pune", Address="Shimla"},  
  8.           new Student{ Id=104, Name="Rohtas", CollegeName="Bhartiya Vidypeeth Pune", Address="Shilong"},  
  9.           new Student{ Id=105, Name="Manish Shristava", CollegeName="MIT Pune", Address="Gangtok"},  
  10.           new Student{ Id=106, Name="Papon", CollegeName=" Pachhunga University College", Address="Aizawl"},  
  11.           new Student{ Id=107, Name="Izlyn", CollegeName=" Pachhunga University College", Address="Aizawl"},  
  12.           new Student{ Id=108, Name="Sha Spazzer", CollegeName="BIT Meshra", Address="Kohima"},  
  13.           new Student{ Id=109, Name="Soo yang", CollegeName="MIT Pune", Address="Kohima"},  
  14.           new Student{ Id=110, Name="Manish Singh", CollegeName="MIT Pune", Address="New Delhi"}  
  15.        };  
  16.     }  
Step 6

Small changes in RouteConfig class:
  1. public class RouteConfig  
  2.    {  
  3.        public static void RegisterRoutes(RouteCollection routes)  
  4.        {  
  5.            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
  6.   
  7.            routes.MapRoute(  
  8.                name: "Home",  
  9.                url: "{controller}/{action}/{id}",  
  10.                defaults: new { controller = "Home", action = "Details", id = UrlParameter.Optional }  
  11.            );  
  12.        }  
  13.    }  
This code is responsible for creating the link to ApiController from the MVC controller StudentController that is the MVC controller responsible for dealing with the students class. To generate the link, we can call a Link method on the UrlHelper and pass in the relevant route defaults.

Step 7

In this step we will create the ApiController.

  1. public class StudentController : ApiController  
  2.    {  
  3.        public Student GetById(int id)  
  4.        {  
  5.            var stud = Students.List.FirstOrDefault(x => x.Id == id);  
  6.            if (stud == nullthrow new HttpResponseException(HttpStatusCode.NotFound);  
  7.            stud.Link = Url.Link("Home"new { controller = "Home", action = "Index", id = id });  
  8.            //  /api/Values/101  
  9.            return stud;  
  10.        }  
  11.    }  
A link in the opposite direction, from ApiController to MVCController. MVC specific UrlHelper is used with the HttpRouteUrl extension method. 

Step 8

In this step we will create the MVC controller. This is the main controller, where we can use a linking to the ASP.NET Web API to MVC Controller.

  1. public class HomeController : Controller  
  2.   {  
  3.       public ActionResult Index(int id)  
  4.       {  
  5.           var stud = Students.List.FirstOrDefault(x => x.Id == id);  
  6.           if (stud == nullreturn new HttpNotFoundResult();  
  7.           stud.Link = Url.HttpRouteUrl("DefaultApi"new { controller = "Student", id = id });  
  8.   
  9.           return View(stud);  
  10.       }  
  11.       public ActionResult Details()  
  12.       {  
  13.              return View(Students.List);  
  14.       }  
  15.   }  

Output 

Display all the records where we need to click on the Name of the any contact as in the Hyperlink.

DisplayAll

After clicking the link we are able to see the specific result as we have selected. And also get the new Link to see the Web API on the ID basis.

SelectedRecord

WebApi

Summary

In this article we learned the linking of a MVC Controller to an API Controller. For that we have used two controllers and made a simple setting in the RouteConfig class. I hope this article will help you somewhere. 

Further Reading

<< Getting Started with ASP.NET Web API 2 : Day 4