Call Asp.net Web API from C#

If you search in the web for calling web API from C# Code not from URL, you will find lots of sample on get and hardly enough on POST! I don't know why but I want to share with you a simple example. As a usual open visual studio and create a web API project from MVC project template.

Suppose these two simple post and get API actions:

  1.         [HttpPost]
  2.         [Route("api/Test/PostValue")]
  3.         public IHttpActionResult PostValue([FromBody]string value)
  4.         {
  5.             //Persis in data base or what you want
  6.             return Ok();
  7.         }
  8.  
  9.         [HttpGet]
  10.         [Route("api/Test/GetValue")]
  11.         public IHttpActionResult GetValue()
  12.         {
  13.             //Fetch from data base
  14.             return Ok();
  15.         }

Now We want to post a data to the PostValue and get a data from GetValue considering the parameters of the Post is FromBody which means that you should send the target value from body of your request not in Url in the case of calling by postman or other tools. To call the above action methods from c#, simply create an instance of HttpClient and call the appropriate methods:

  1.   public ActionResult Post()
  2.         {
  3.             var client = new HttpClient();
  4.             var response = client.PostAsJsonAsync("http://localhost:52863/" + "/Api/Test/PostValue", "a value for api").Result;
  5.             return View();
  6.         }
  7.  
  8.  
  9.         public ActionResult Get()
  10.         {
  11.             var client = new HttpClient();
  12.             var response = client.GetAsync("http://localhost:52863/" + "/Api/Test/GetValue");
  13.             return View();
  14.         }

 or simply call them in a console application to see the result.


Tags: C# Asp.Net Web API


comments powered by Disqus