Go to Comments





How to create Asp Net Web Api project and call the Web Api from c# csharp


Created: 18/04/2015 06:42:48 p.m.





How to create Asp Net Web Api project and call the Web Api from c# csharp
( Asp.net web api tutorial )
(This example return data in JSON format.)
(Building RESTful app)

(Part 1) - How to create asp net web api project



Framework used: 4.0!

1) So lets start, first just create an MVC 4 or 3 Application





2) Select Web Api and press OK.





3) Now we have created our simple Web Api project, lets add some features.





4) In this case i want to return the data in JSON format, just add this code to the WebApiConfig.


            // We want to return only Json data.
            config.Formatters.Clear();
            config.Formatters.Add(new System.Net.Http.Formatting.JsonMediaTypeFormatter());






5) Create simple entity, for example person, later we will return list of people through JSON format.




6) Now in the sample method Get(), make some changes like this one.

I just created a list of persons and return this list to the caller, this one we will create later.




7) Finally compile your project and try it out.

call the method and you must obtain the list of persons.






(Part 2) - Call the web api from c#

Now we will call/consume our Api


1) Create simple console app.




2) Add the following reference. This will allow us to deserialize the json to c# objects.



and dont forget to include this Usings in your app:

using System.Net;
using System.Web;
using System.Web.Script.Serialization;
using System.IO;


3) This is a sample code of how you can consume/call your Api.


        static void callApiMethodGet()
        {
            WebRequest req = WebRequest.Create("http://localhost:16053/api/values");
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            var strResult = new StreamReader(resp.GetResponseStream()).ReadToEnd();

            JavaScriptSerializer jss = new JavaScriptSerializer();

            List<person> people = jss.Deserialize<List<person>>(strResult);

            foreach (person per in people)
            {
                Console.WriteLine("Name: " + per.name + ", age: " + per.age);
            }
        }




4) Compile and now we can see that our call returned 2 objects the two ones that we have created in our Api Get() method. Cool! everything works correctly!





5) This is the general panorama of the both applications running, Web Api (Api) and the Console (Caller)



Download 2 projects: DOWNLOAD 



This is just a simple example of how to use Rest Api in .net
if you have any suggestion, just let your comment below.






Comments: