Consuming Web API In ASP.NET MVC - Part Two

n this article, we have used the localhost for Web API and called the GET request.

  • Create ASP.NET MVC Project
  • Add MemberViewModel
  • Add Microsoft.AspNet.webApi.Client from the NuGet library
  • Code for consuming the Web API
  • Run the project and call action method on URL

Step by step implementation:

Step 1

Create a new ASP.NET MVC Web Application project called “ConsumeWebApiMVC”.

 
 
 
                                        
                                        
 

The default project files in the Solution Explorer look like the following.

                                           
 
 
 
 
Now, create a ViewModel called MemberViewModel inside the Models folder.

Right-click on Models folder. Go to Add --> New Item or press CTRL + SHIFT + A.


MemberViewModel.cs Code

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. namespace ConsumeWebApiMVC.Models
  6. {
  7. public class MemberViewModel
  8. {
  9. public int MemberID { get; set; }
  10. public string MemberName { get; set; }
  11. public string PhoneNumber { get; set; }
  12. }
  13. }

You can see HomeControllers inside the Controllers folder. Double-click on HomeControllers and add the following line for getting ViewModel listing in the controller.

  1. using ConsumeWebApiMVC.Models;

Now, add Microsoft.AspNet.webApi.Client from the NuGet library.

Right-click on References folder and select it.



Click OK as in the above dialog box to install Microsoft.AspNetWebApi.Client.

Click on "I Accept" to confirm the installation again.

You can see in the output window that the NuGet package is successfully installed.

After adding the NuGet package, now, let us code for consuming the Web API and calling the get method of all members' records.

  1. public ActionResult GetMembers()
  2. {
  3. IEnumerable<MemberViewModel> members = null;
  4. using (var client = new HttpClient())
  5. {
  6. client.BaseAddress = new Uri("http://localhost:52044/api/");
  7. //Called Member default GET All records
  8. //GetAsync to send a GET request
  9. // PutAsync to send a PUT request
  10. var responseTask = client.GetAsync("member");
  11. responseTask.Wait();
  12. //To store result of web api response.
  13. var result = responseTask.Result;
  14. //If success received
  15. if (result.IsSuccessStatusCode)
  16. {
  17. var readTask = result.Content.ReadAsAsync<IList<MemberViewModel>>();
  18. readTask.Wait();
  19. members = readTask.Result;
  20. }
  21. else
  22. {
  23. //Error response received
  24. members = Enumerable.Empty<MemberViewModel>();
  25. ModelState.AddModelError(string.Empty, "Server error try after some time.");
  26. }
  27. }
  28. return View(members);
  29. }
  30. var responseTask = client.GetAsync("member");

The following are the methods of HttpClient:

SR. NO.HTTP CLIENT METHODSDESCRIPTION
1Client.GetAsyncTo send GET request.
2Client.PostAsyncTo send POST request.
3Client.PutAsyncTo send PUT request.
4Client.DeleteAsyncTo send DELETE request.

Now, add a View for GetMembers. Right-click on GetMembers Action Method.

After clicking on "Add View" option, fill the Add View form.

Then, click the Add button to proceed further.

Now, you can see GetMembers.cshtml file created inside VIEWS --> HOME folder.

Now, let us check our Web API code by pressing F5.

http://localhost:50604/home/getmembers

In the next article, you will learn how to call Web API through jQuery.

 

Up Next
    Ebook Download
    View all
    Learn
    View all
    sourabhsomani.com