I'm trying to create a Helper Controller that will essentially make a GET request to a Web API to create a list that will eventually be used to return JSON data. I found an example online that almost does what I want except that the data is hard-coded within the controller.
Controller (In C#):
public class StudentAPIController : Controller
{
// GET: api/GetAllStudents
[HttpGet]
public IEnumerable<PersonalDetail> GetAllStudents()
{
List<PersonalDetail> students = new List<PersonalDetail>
{
string uri = "URL_OF_API_CALL";
new PersonalDetail{
// Here is where I want to make the API call to fetch the data instead of this hard-coded data
RegNo = "2017-0001",
Name = "Nishan",
Address = "Kathmandu",
PhoneNo = "9849845061",
AdmissionDate = DateTime.Now
},
new PersonalDetail{
RegNo = "2017-0002",
Name = "Namrata Rai",
Address = "Bhaktapur",
PhoneNo = "9849845062",
AdmissionDate = DateTime.Now
},
};
return students;
}
}
Any help is greatly appreciated!
First add this library :
System.Net.Http
Then you can use these line of codes to call another web api in your helper controller:
HttpClient client = new HttpClient();
client.BaseAddress = @"http://[YourBaseUri]/";
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var request = client.GetAsync("[YourActionName]");
return request.Result.Content.ReadAsStringAsync().Result;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.