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
        public ActionResult Student()
            string apiUrl = string.Format("");
            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 
            return View();

        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()))
                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. Required fields are marked *


Select Categories