GET Method(s)

Go to previous
We simply assume that the Web API GET method conforms to Microsoft philosophy ragarding REST webservice methods. Like this:
// GET: api/Employee [HttpGet] public IEnumerable Get() . . . // GET: api/Employee/5 [HttpGet("{id}", Name = "Get")] public Employee Get(int id)
So we can write the MVC Controller methods as follows:
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using MyAspNetCoreApplication.Models; using System.Net.Http; using System.Net.Http.Headers; using Newtonsoft.Json; //Get all Employees public async Task GetAllEmployees() { List EmpInfo = new List (); using (var client = new HttpClient()) { var Url = "http://" + HttpContext.Request.Host.Value + "/api/Employee"; //Passing service base url client.BaseAddress = new Uri(Url); client.DefaultRequestHeaders.Clear(); ////Define request data format client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); //Sending request to find web api REST service resource GetAllEmployees using HttpClient HttpResponseMessage Res = await client.GetAsync("Employee"); //Checking the response is successful or not which is sent using HttpClient if (Res.IsSuccessStatusCode) { //Storing the response details recieved from web api var EmpResponse = Res.Content.ReadAsStringAsync().Result; //Deserializing the response recieved from web api and storing into the Employee list EmpInfo = JsonConvert.DeserializeObject>(EmpResponse); } //returning the employee list to view return View(EmpInfo); } } //Get an Employee with a certain ID public async Task GetEmployee(int Id) { Employee EmpInfo = new Employee(); using (var client = new HttpClient()) { var Url = "http://" + HttpContext.Request.Host.Value + "/api/Employee"; client.BaseAddress = new Uri(Url); client.DefaultRequestHeaders.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage Res = await client.GetAsync("Employee/"+Id); if (Res.IsSuccessStatusCode) { var EmpResponse = Res.Content.ReadAsStringAsync().Result; //Deserializing the response recieved from web api and storing into the Employee object EmpInfo = JsonConvert.DeserializeObject(EmpResponse); } return View(EmpInfo); } }