Consume Web API Get Method In ASP.NET MVC Using Http Client

In this article, We will learn about the consume Web API Get method in ASP.NET MVC using HTTP Client.

The HttpClient sends a request to the Web API and receives a response. We then need to convert that response data to a model and then render it into a view.

We already created the Web API GET Method which is shown below.

namespace CycleWebAPICodeFirst.Controllers
{
    [Route("[controller]")]
    [ApiController]
    public class CycleController : ControllerBase
    {
        private readonly ISqlHelper _sqlHelper;
       
        public CycleController(ISqlHelper sqlHelper)
        {
            _sqlHelper = sqlHelper;
        }
       
        [HttpGet("GetAllCycle")]
        public IActionResult Get()
        {
            List<Cycle> cycle= _sqlHelper.GetCycleData();
            if (cycle.Count==0)
                return NotFound("Cycle Data Empty");

            return Ok(cycle);
        }
    }
}

As we can see web API Get ActionMethod in the above code will handle HTTP GET request “https://localhost:44368/Cycle/GetAllCycle” and return a list of cycle data. We will send this HTTP request in the ASP.NET MVC controller to get all the Cycle records and display them in the MVC View.

Here, We will consume this GET Web API by following the below steps,

Step 1.  Create model class according to how response we get from HTTP GET Web API. As per our example, our model class is as below.

public class Cycle
{
    public int ID { get; set; }
    public string CycleName { get; set; }
    public string Company { get; set; }
    public int Price { get; set; }
    public string Colour { get; set; }
    public int Size { get; set; }
    public string Image { get; set; }
}

Step 2. Create an MVC controller class called “CycleController.cs” which is shown below.

public class CycleController : Controller
 {
   
     public ActionResult Index()
     {
         return View();
     }
 }

Step 3. We need to access GET web API, For that, we have to create an action method and access API into that action method as shown below.

public class CycleController : Controller
   {
       
       public ActionResult Index()
       {
           return View();
       }

       public ActionResult GetCycles()
       {
           IEnumerable<Cycle> cycles = null;

           using(var client =new HttpClient())
           {
               client.BaseAddress = new Uri("https://localhost:44368/Cycle/");

               var responseTask = client.GetAsync("GetAllCycle");
               responseTask.Wait();

               var result = responseTask.Result;
               if (result.IsSuccessStatusCode)
               {
                   var readTask = result.Content.ReadAsAsync<IList<Cycle>>();
                   readTask.Wait();

                   cycles = readTask.Result;
               }
               else
               {
                   cycles = Enumerable.Empty<Cycle>();
                   ModelState.AddModelError(string.Empty, "server error,Contact Administrator");
               }
           }
           return View(cycles);
       }
   }

Step 4. Now, we need to add “GetCycles.cshtml” view. Right-click in the GetCycles action method and select Add View option. This will open Add View popup as shown below. Now, select List as the template and Cycle as the Model class as below (we already created the Cycle model as above).

Now, Click on Add button to add the “GetCycle” view into the View folder. and this will generate the view file as shown below.

@model IEnumerable<Test_Consume_web_api.Models.Cycle>

@{
    ViewBag.Title = "GetCycles";
}

<h2>GetCycles</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.CycleName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Company)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Price)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Colour)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Size)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Image)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.CycleName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Company)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Price)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Colour)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Size)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Image)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
            @Html.ActionLink("Details", "Details", new { id=item.ID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.ID })
        </td>
    </tr>
}

</table>

Now, run the application and you will see the out as shown below.

Display Error :

We have successfully displayed records in the view above but what if Web API returns an error response?

To display an appropriate error message in the MVC view, add the ValidationSummary() as shown below.

@model IEnumerable<Test_Consume_web_api.Models.Cycle>

@{
    ViewBag.Title = "GetCycles";
}

<h2>GetCycles</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.CycleName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Company)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Price)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Colour)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Size)
        </th>       
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.CycleName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Company)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Price)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Colour)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Size)
        </td>      
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
            @Html.ActionLink("Details", "Details", new { id=item.ID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.ID })
        </td>
    </tr>
}
<tr>
    <td>
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    </td>
</tr>

</table>

In the above view, we have added @Html.ValidationSummary(true, “”, new { @class = “text-danger” }) in the last row of the table. This is to display an error message if Web API returns an error response with a status code other than 200 OK.

So, if web API returns any kind of error or any other status code other than 200 ok then it will give output as shown below.

I hope this article will help you to understand how we can consume HTTP GET web API using HTTP Client.

Thank you.

Submit a Comment

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

Subscribe

Select Categories