• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer
info@dotnettec.com | +91-8800268750

DotNetTec

  • Home
  • Tutorials
    • Programming Language
      • C#
      • JavaScript
    • .Net Development
      • .NET Framework
      • ASP.NET Web Forms
      • MVC Architecture
      • Web API
      • .NET Core Framework
    • Front End Frameworks
      • JavaScript
      • HTML
    • Cloud Computing
      • Microsoft Azure
    • Database
      • SQL Server
    • Google Maps API
    • RPA
      • Blue Prism
      • UiPath
  • How to
  • Knowledge Base
  • Shop

Calling Web API from MVC Controller Httpclient

March 23, 2020 by Ravi Kumar Leave a Comment

In this blog post, you will learn how to consume web api in mvc and implementation of calling web api from mvc controller using httpclient. Previously I have explained how to create Web API in ASP.NET C#, how to implement Web API CRUD Operations using ASP.NET MVC and Entity Framework, Pass Multiple Parameters in Web API URL C#

Consume Web API in .NET using HttpClient

ASP.NET Web API is a framework for building HTTP based services that can be consumed from any client including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.

Here we have already created asp.net web api which we have tested using Postman. So the same web api we are going to consume in the MVC 5 application. Just follow the below steps:-

Step 1: Just add a new project named WebAppMVC using the empty template for MVC application so it will create asp.net MVC 5 application for us.

mvc empty template

Step 2: Now we have to do whatever the web api address we have the same web api address we will use for consuming the web api for crud operation.

web api address

Step 3: Now add a new controller named UserController and you can see using the scaffold template it will generate the code for us.

add scaffold template

Step 4: To show the user list we have to consume our web api for crud operation using HttpClient. So, add a reference to System.Net.Http for accessing the HttpClient.

add reference to mvc project

Now create a HttpClient class object and using this we can call web api from MVC controller and other types of applications such as ASP.Net web forms or WPF. Find the below full source code:

UserController.cs

using System;
using System.Collections.Generic;
using System.Web.Mvc;
using System.Net.Http;
using WebAppMVC.Models;
using Newtonsoft.Json;
using System.Text;

namespace WebAppMVC.Controllers
{
    public class UserController : Controller
    {
        Uri baseAddress = new Uri("http://localhost:55117/api");
        HttpClient client;
        public UserController()
        {
            client = new HttpClient();
            client.BaseAddress = baseAddress;
        }
        public ActionResult Index()
        {
            List<UserViewModel> modelList = new List<UserViewModel>();
            HttpResponseMessage response = client.GetAsync(client.BaseAddress + "/user").Result;
            if (response.IsSuccessStatusCode)
            {
                string data = response.Content.ReadAsStringAsync().Result;
                modelList = JsonConvert.DeserializeObject<List<UserViewModel>>(data);
            }
            return View(modelList);
        }

        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Create(UserViewModel model)
        {
            string data = JsonConvert.SerializeObject(model);
            StringContent content = new StringContent(data, Encoding.UTF8, "application/json");

            HttpResponseMessage response = client.PostAsync(client.BaseAddress + "/user", content).Result;
            if (response.IsSuccessStatusCode)
            {
                return RedirectToAction("Index");
            }
            return View();
        }

        public ActionResult Edit(int id)
        {
            UserViewModel model = new UserViewModel();
            HttpResponseMessage response = client.GetAsync(client.BaseAddress + "/user/" + id).Result;
            if (response.IsSuccessStatusCode)
            {
                string data = response.Content.ReadAsStringAsync().Result;
                model = JsonConvert.DeserializeObject<UserViewModel>(data);
            }
            return View("Create", model);
        }

        [HttpPost]
        public ActionResult Edit(UserViewModel model)
        {
            string data = JsonConvert.SerializeObject(model);
            StringContent content = new StringContent(data, Encoding.UTF8, "application/json");

            HttpResponseMessage response = client.PutAsync(client.BaseAddress + "/user/" + model.UserId, content).Result;
            if (response.IsSuccessStatusCode)
            {
                return RedirectToAction("Index");
            }
            return View("Create", model);
        }

        public ActionResult Delete(int id)
        {
            HttpResponseMessage response = client.DeleteAsync(client.BaseAddress + "/user/" + id).Result;
            if (response.IsSuccessStatusCode)
            {
                return RedirectToAction("Index");
            }
            return RedirectToAction("Index");
        }
    }
}

Index.cshtml

@model IEnumerable<WebAppMVC.Models.UserViewModel>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.UserId)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Address)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Contact)
        </th>
        <th></th>
    </tr>

    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.UserId)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Name)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Address)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Contact)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { id = item.UserId }) |
                @Html.ActionLink("Delete", "Delete", new { id = item.UserId }, new { onclick = "return confirm('Are you sure to delete?')" })
            </td>
        </tr>
    }
</table>

Create.cshtml

@model WebAppMVC.Models.UserViewModel

@{
    ViewBag.Title = Model != null ? "Edit" : "Create";
}

<h2>@ViewBag.Title</h2>
<hr />

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        @Html.HiddenFor(model => model.UserId)
        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Contact, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Contact, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Contact, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Save" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

Download Source Code

Conclusion

I hope you liked this article on how to call (consume) web api from mvc controller using httpclient. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

Category iconASP.NET Web API,  How to Tag iconcall web api from mvc controller,  calling web api from mvc controller httpclient,  consume web api in mvc,  how to call web api in asp.net c#

Subscribe to our blog.

Get the latest posts delivered right to your inbox.

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

Recent Posts

  • Google Maps Draw Polygon Get Coordinates
  • Check if point inside polygon Google Maps JavaScript
  • How to Create a Calendar Control in ASP.NET
  • Interview Etiquette Before, During and After
  • How to Attend Telephonic Interview Tips

Products

  • Online Shopping ASP.NET Project Source Code Online Shopping ASP.NET Project Source Code
    Rated 5.00 out of 5
    $69.00 $39.00
  • responsive-aspnet-mvc-grid-view ASP.NET MVC full Ajaxify and Bootstrap Grid with CRUD Operation
    Rated 4.67 out of 5
    $21.00 $9.00
  • eCommerce Website Source Code in ASP.NET eCommerce Website Source Code in ASP.NET $99.00
  • Hospital Management System Project ASP.Net Source Code
    Rated 5.00 out of 5
    $99.00
  • Whatsapp Bulk Message Sender Source Code WhatsApp Bulk Message Sender Source Code
    Rated 5.00 out of 5
    $69.00

Footer

.NET Developers Blog

Learn .NET, Programming Languages, Web App Development, APIs Development & Integration, Google Maps JavaScript APIs, and Cloud Services, through the latest articles, step-by-step tutorials, code examples, live projects, interview ebooks, and best practices.

Sitemap

  • About
  • Blog
  • Shop
  • Contact
  • Privacy Policy

Expertise

  • Web Development
  • Custom Software Development
  • Web API Development
  • Google Maps APIs

Newsletter

Get the latest news, posts, and announcements straight to your inbox.

Copyright © 2021 DotNetTec.