
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Consume ASP.NET Web API Endpoints Using C#
HttpClient class provides a base class for sending/receiving the HTTP requests/responses from a URL. It is a supported async feature of .NET framework. HttpClient is able to process multiple concurrent requests. It is a layer over HttpWebRequest and HttpWebResponse. All methods with HttpClient are asynchronous. HttpClient is available in System.Net.Http namespace.
Let us create an WebAPI application having a StudentController and respective action methods.
Student Model
namespace DemoWebApplication.Models{ public class Student{ public int Id { get; set; } public string Name { get; set; } } }
Student Controller
using DemoWebApplication.Models; using System.Collections.Generic; using System.Linq; using System.Web.Http; namespace DemoWebApplication.Controllers{ public class StudentController : ApiController{ List<Student> students = new List<Student>{ new Student{ Id = 1, Name = "Mark" }, new Student{ Id = 2, Name = "John" } }; public IEnumerable<Student> Get(){ return students; } public Student Get(int id){ var studentForId = students.FirstOrDefault(x => x.Id == id); return studentForId; } } }
Now, let us create a console application where we want consume the above created WebApi endpoints to get the student details.
Example
using System; using System.Net.Http; namespace DemoApplication{ public class Program{ static void Main(string[] args){ using (var httpClient = new HttpClient()){ Console.WriteLine("Calling WebApi for get all students"); var students = GetResponse("student"); Console.WriteLine($"All Students: {students}"); Console.WriteLine("Calling WebApi for student id 2"); var studentForId = GetResponse("student/2"); Console.WriteLine($"Student for Id 2: {students}"); Console.ReadLine(); } } private static string GetResponse(string url){ using (var httpClient = new HttpClient()){ httpClient.BaseAddress = new Uri("http://localhost:58174/api/"); var responseTask = httpClient.GetAsync(url); var result = responseTask.Result; var readTask = result.Content.ReadAsStringAsync(); return readTask.Result; } } } }
Output
Calling WebApi for get all students All Students: [{"Id":1,"Name":"Mark"},{"Id":2,"Name":"John"}] Calling WebApi for student id 2 Student for Id 2: {"Id":2,"Name":"John"}
In the above example we could see that the endpoints of the WebApi is called from a separate console application.
Advertisements