Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Calling Web API from MVC Controller Httpclient

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.

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.

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.

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

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.

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 modelList = new List();
            HttpResponseMessage response = client.GetAsync(client.BaseAddress + "/user").Result;
            if (response.IsSuccessStatusCode)
            {
                string data = response.Content.ReadAsStringAsync().Result;
                modelList = JsonConvert.DeserializeObject>(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(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

@{
    ViewBag.Title = "Index";
}

Index

@Html.ActionLink("Create New", "Create")

@foreach (var item in Model) { }
@Html.DisplayNameFor(model => model.UserId) @Html.DisplayNameFor(model => model.Name) @Html.DisplayNameFor(model => model.Address) @Html.DisplayNameFor(model => model.Contact)
@Html.DisplayFor(modelItem => item.UserId) @Html.DisplayFor(modelItem => item.Name) @Html.DisplayFor(modelItem => item.Address) @Html.DisplayFor(modelItem => item.Contact) @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?')" })

Create.cshtml

@model WebAppMVC.Models.UserViewModel

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

@ViewBag.Title


@using (Html.BeginForm()) { @Html.AntiForgeryToken()
@Html.ValidationSummary(true, "", new { @class = "text-danger" }) @Html.HiddenFor(model => model.UserId)
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.Contact, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Contact, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Contact, "", new { @class = "text-danger" })
}

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.

The post Calling Web API from MVC Controller Httpclient appeared first on DotNetTec.



This post first appeared on Asp Dot Net Tricks And Tips, Dot Net Coding Tips, Google Maps API Developer, please read the originial post: here

Share the post

Calling Web API from MVC Controller Httpclient

×

Subscribe to Asp Dot Net Tricks And Tips, Dot Net Coding Tips, Google Maps Api Developer

Get updates delivered right to your inbox!

Thank you for your subscription

×