Ehsan Ghanbari

Experience, DotNet, Solutions

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 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.

About Me

Ehsan Ghanbari

Hi! my name is Ehsan. I'm a developer, passionate technologist, and fan of clean code. I'm interested in enterprise and large-scale applications architecture and design patterns. I'm spending a lot of my time on software architecture. Since 2008, I've been as a developer for companies and organizations and I've been focusing on Microsoft ecosystem all the time. During the Read More

Post Tags
Pending Blog Posts
Strategic design
Factory Pattern
time out pattern in ajax
Selectors in Jquery
using Log4net in asp.net MVC4
Redis as a cache server
How to use PagedList In asp.net MVC
Multiple submit buttons in asp.net MVC
Domain driven design VS model driven architecture
What's the DDD-lite?
comments powered by Disqus