Blog

Filter posts by the Tags of Blog section!

Call Asp.net Web API from C# Tuesday, 05 January 2016

If you search in the web for calling web API from C# Code, not from URL, you will find lots of sample on getting and hard enough on the 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 the MVC project template.

Suppose these two simple post and get API actions:     

   [HttpPost]

        [Route("api/Test/PostValue")]

        public IHttpActionResult PostValue([FromBody]string value)

        {

            //Persis in data base or what you want

            return Ok();

        }



        [HttpGet]

        [Route("api/Test/GetValue")]

        public IHttpActionResult GetValue()

        {

            //Fetch from data base

            return Ok();

        }

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 the 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:

  public ActionResult Post()

        {

            var client = new HttpClient();

            var response = client.PostAsJsonAsync("http://localhost:52863/" + "/Api/Test/PostValue", "a value for api").Result;

            return View();

        }





        public ActionResult Get()

        {

            var client = new HttpClient();

            var response = client.GetAsync("http://localhost:52863/" + "/Api/Test/GetValue");

            return View();

        }

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

comments powered by Disqus