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.
- public class RouteConfig
- {
- public static void RegisterRoutes(RouteCollection routes)
- {
- routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
-
- routes.MapRoute(
- name: "Home",
- url: "{controller}/{action}/{id}",
- defaults: new { controller = "Home", action = "Details", id = UrlParameter.Optional }
- );
- }
- }
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 StartedIn 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 2Select the ASP.NET Web Application and provide a nice name for the project.
Step 3Select the Web API template and click the OK button.
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.
- public class Student
- {
- public int Id { get; set; }
- public string Name { get; set; }
- public string Address { get; set; }
- public string CollegeName { get; set; }
- public string Link { get; set; }
- }
Step 5
Add another Students class to the model where we field some dummy data inside into as in List.
- public class Students
- {
- public static List<Student> List = new List<Student>
- {
- new Student{ Id=101, Name="Rajeev Ranjan", CollegeName="MIT Pune", Address="New Delhi"},
- new Student{ Id=102, Name="Ashwani Gupta", CollegeName="D Y Patil College of Engineering Pune", Address="Hazaribagh"},
- new Student{ Id=103, Name="Nimit Joshi", CollegeName="Bhartiya Vidypeeth Pune", Address="Shimla"},
- new Student{ Id=104, Name="Rohtas", CollegeName="Bhartiya Vidypeeth Pune", Address="Shilong"},
- new Student{ Id=105, Name="Manish Shristava", CollegeName="MIT Pune", Address="Gangtok"},
- new Student{ Id=106, Name="Papon", CollegeName=" Pachhunga University College", Address="Aizawl"},
- new Student{ Id=107, Name="Izlyn", CollegeName=" Pachhunga University College", Address="Aizawl"},
- new Student{ Id=108, Name="Sha Spazzer", CollegeName="BIT Meshra", Address="Kohima"},
- new Student{ Id=109, Name="Soo yang", CollegeName="MIT Pune", Address="Kohima"},
- new Student{ Id=110, Name="Manish Singh", CollegeName="MIT Pune", Address="New Delhi"}
- };
- }
Step 6
Small changes in RouteConfig class:
- public class RouteConfig
- {
- public static void RegisterRoutes(RouteCollection routes)
- {
- routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
-
- routes.MapRoute(
- name: "Home",
- url: "{controller}/{action}/{id}",
- defaults: new { controller = "Home", action = "Details", id = UrlParameter.Optional }
- );
- }
- }
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.
- public class StudentController : ApiController
- {
- public Student GetById(int id)
- {
- var stud = Students.List.FirstOrDefault(x => x.Id == id);
- if (stud == null) throw new HttpResponseException(HttpStatusCode.NotFound);
- stud.Link = Url.Link("Home", new { controller = "Home", action = "Index", id = id });
-
- return stud;
- }
- }
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.
- public class HomeController : Controller
- {
- public ActionResult Index(int id)
- {
- var stud = Students.List.FirstOrDefault(x => x.Id == id);
- if (stud == null) return new HttpNotFoundResult();
- stud.Link = Url.HttpRouteUrl("DefaultApi", new { controller = "Student", id = id });
-
- return View(stud);
- }
- public ActionResult Details()
- {
- return View(Students.List);
- }
- }
Output
Display all the records where we need to click on the Name of the any contact as in the Hyperlink.
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.
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