In this article I will explain with an example, how to call Web API from MVC Controller in same Solution (Project) in ASP.Net MVC Razor.
This article will illustrate how to call a Web API method using its URL from another project in same Project or same Solution in ASP.Net MVC Razor.
 
 
Database
Here I am making use of Microsoft’s Northwind Database. You can download it from here.
 
 
Entity Framework Model
Once the Entity Framework is configured and connected to the database table, the Model will look as shown below.
Note : For beginners in ASP.Net MVC and Entity Framework, please refer my article ASP.Net MVC: Simple Entity Framework Tutorial with example. It covers all the information needed for connecting and configuring Entity Framework.
 
Call Web API from MVC Controller in same Solution (Project)
 
 
Model
The CustomerModel class consists of the following property.
public class CustomerModel
{
    ///<summary>
    /// Gets or sets Name.
    ///</summary>
    public string Name { get; set; }
}
 
 
Web API Controller
In order to add a Web API Controller you will need to Right Click the Controllers folder in the Solution Explorer and click on Add and then Controller.
Now from the Add Scaffold window, choose the Web API 2 Controller – Empty option as shown below.
Call Web API from MVC Controller in same Solution (Project)
 
Then give it a suitable name and click OK.
Call Web API from MVC Controller in same Solution (Project)
 
The next task is to register the Configuration for Web API in the Global.asax file so that the Web API is available for accessing on Web.
In order to do so open Global.asax file and add the following line.
System.Web.Http.GlobalConfiguration.Configure(WebApiConfig.Register);
 
Make sure you add it in the same order as shown below.
public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        System.Web.Http.GlobalConfiguration.Configure(WebApiConfig.Register);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
    }
}
 
The next step is to code the Web API Controller. The Web API Controller consists of a method named GetCustomers which accepts an object of CustomerModel.
The records of the Customers are fetched using Entity Framework and are filtered using the StartsWith function based on the value of the Name property.
Finally, the records are returned as Generic List Collection.
This method is decorated with Route attribute which defines its Route for calling the Web API method and HttpPost attribute which signifies that the method will accept Http Post requests.
public class CustomerAPIController : ApiController
{
    [Route("api/CustomerAPI/GetCustomers")]
    [HttpPost]
    public List<Customer> GetCustomers(CustomerModel customer)
    {
        NorthwindEntities entities = new NorthwindEntities();
        return (from c in entities.Customers.Take(10)
                where c.ContactName.StartsWith(customer.Name) || string.IsNullOrEmpty(customer.Name)
                select c).ToList();
    }
}
 
 
Namespaces
You will need to import the following namespaces.
using System.Net;
using System.Text;
using System.Web.Script.Serialization;
 
 
Model
The CustomerModel class consists of the following properties.
public class CustomerModel
{
    public string CustomerID { get; set; }
    public string ContactName { get; set; }
    public string City { get; set; }
}
 
 
Controller
The Controller consists of following two Actions method.
Action method for handling GET operation
Inside this Action method, the SearchCustomers method is called with empty string value as parameter and a Generic List of CustomerModel class objects is returned to the View.
Inside the SearchCustomers method, the value of the Name parameter is wrapped into a JSON object which is then serialized into a JSON string.
The URL of the Web API along with its Controller method and the serialized JSON string is passed to the UploadString method of the WebClient class.
The UploadString method of the WebClient class calls the Web API’s Controller method i.e. the GetCustomers method and returns the JSON string which is then de-serialized to Generic List of CustomerModel class objects.
 
Action method for handling POST operation
This Action method is called when the Form is submitted. Here also the SearchCustomers method is called, but the only difference is that the value of the TextBox received from the View is passed as parameter.
public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        List<CustomerModel> customers = SearchCustomers("");
        return View(customers);
    }
 
    [HttpPost]
    public ActionResult Index(string name)
    {
        List<CustomerModel> customers = SearchCustomers(name);
        return View(customers);
    }
 
    private staticList<CustomerModel> SearchCustomers(string name)
    {
        string apiUrl = "http://localhost:26404/api/CustomerAPI";
        var input = new
        {
            Name = name,
        };
        string inputJson = (new JavaScriptSerializer()).Serialize(input);
        WebClient client = new WebClient();
        client.Headers["Content-type"] = "application/json";
        client.Encoding = Encoding.UTF8;
        string json = client.UploadString(apiUrl + "/GetCustomers", inputJson);
        List<CustomerModel> customers = (new JavaScriptSerializer()).Deserialize<List<CustomerModel>>(json);
        return customers;
    }
}
 
 
View
Inside the View, in the very first line the CustomerModel class is declared as IEnumerable which specifies that it will be available as a Collection.
For displaying the records, an HTML Table is used. A loop will be executed over the Model which will generate the HTML Table rows with the Customer records.
The View also consists of an HTML Form which has been created using the Html.BeginForm method with the following parameters.
ActionName – Name of the Action. In this case the name is Index.
ControllerName – Name of the Controller. In this case the name is Home.
FormMethod – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
Inside the Form, there is a TextBox and a Submit Button.
@using MVC_App.Models
@model IEnumerable<CustomerModel>
 
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    @using (Html.BeginForm("Index", "Home", FormMethod.Post))
    {
        <span>Name:</span>
        <input type="text" name="name"/>
        <input type="submit" value="Search"/>
    }
    <hr/>
    <table cellpadding="0" cellspacing="0">
        <tr>
            <th>CustomerID</th>
            <th>ContactName</th>
            <th>City</th>
        </tr>
        @foreach (CustomerModel customer in Model)
        {
            <tr>
                <td>@customer.CustomerID</td>
                <td>@customer.ContactName</td>
                <td>@customer.City</td>
            </tr>
        }
    </table>
</body>
</html>
 
 
Screenshot
Call Web API from MVC Controller in same Solution (Project)
 
 
Downloads