Consume API In C# Code Using WebRequest

In This Article we will learn How to Call API for your MVC Project.

Now, Let’s Start

Step1: First Create New MVC Project.

Step2: Write below code in your controller.

using System.IO;
using System.Net;
using System.Web.Mvc;

namespace Using_HttpClient_Call_API.Controllers
{
    public class HomeController : Controller
    {
        //GetMethod
        public ActionResult Student()
        {
            string apiUrl = string.Format("https://student-api.mycodelibraries.com/api/student/get");
            WebRequest requestObj = WebRequest.Create(apiUrl);
            requestObj.Method = "GET";
            HttpWebResponse responseObj = null;
            responseObj = (HttpWebResponse)requestObj.GetResponse();

            using (Stream stream = responseObj.GetResponseStream()) 
            {
                StreamReader sr = new StreamReader(stream);
                apiUrl = sr.ReadToEnd();            //Here you can get apiurl for Api response 
                sr.Close();
            }
            return View();
        }

        //PostMethod
        public ActionResult AddStudent()
        {
            string apiUrl = string.Format("https://localhost:44321/api/Students");
            WebRequest requestObjPost = WebRequest.Create(apiUrl);
            requestObjPost.Method = "POST";
            requestObjPost.ContentType = "application/json";
            HttpWebResponse responseObj = null;
            responseObj = (HttpWebResponse)requestObjPost.GetResponse();
            string studentData = "{\"firstName\":\"sddsa\",\"lastName\":\"sdsds\",\"hobbies\":\"false\",\"gender\":\"Male\",\"city\":\"New Delhi\",\"_id\":\"62a70a2d3180872dd88a0230\",\"age\":12,\"createdAt\":\"2022-06-13T09: 58:05.559Z\",\"updatedAt\":\"2022-06-13T09:58:05.559Z\",\"__v\":0}";
            using (var streamWriter = new StreamWriter(requestObjPost.GetRequestStream()))
            {
                streamWriter.Write(studentData);
                streamWriter.Flush();
                streamWriter.Close();
                var httpResponse = (HttpWebResponse)requestObjPost.GetResponse();
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    var result = streamReader.ReadToEnd();   //Here Read your post data
                }
            }
            return View();
        }
    }

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories