16
Feb
2023
2023
Calling Web api from Server Side using Asp.Net Core
by Shubham Batra
129
HttpClient
For calling any web api from server side in Asp.Net we can use HttpClient. it basically ask for Base address where you have hosted the api and then the api url and you can pass parameters using c# and thus can consume the api
For using this follow the steps
Copy following code where you want to call the api from asp.net. Install Newtonsoft.Json nuget package in your application
using System.Net.Http;
using Newtonsoft.Json;
public async Task<IActionResult> Index() { try { Department obj = new Department(); using (var client = new HttpClient()) { client.BaseAddress = new Uri("https://localhost:44347"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = await client.GetAsync("api/Department/GetDepartment?id=1"); List<KeyValuePair<string, string>> values = new List<KeyValuePair<string, string>>() { new KeyValuePair<string, string>("DepartmentId", "1"), new KeyValuePair<string, string>("DepartmentName", "test") }; FormUrlEncodedContent requestContent = new FormUrlEncodedContent(values); HttpResponseMessage response1 = await client.PostAsync("api/Department/SetDepartment", requestContent); if (response.IsSuccessStatusCode) { var result = response.Content.ReadAsStringAsync().Result; obj = JsonConvert.DeserializeObject<Department>(result); } //Send HTTP requests from here. } } catch(Exception ex) { } return View(); }
Here in the BaseAddress , you have to add the url where your api is hosted. In client.GetAsync we have to add the api url.After this run the application and it will hit the api from c#.
So this is how we can implement Calling Web api from Server Side using Asp.Net Core.