Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

JSON and RESTful Web Services using ASP.NET MVC WebApi – What Every Web Programmer Should Know !

4.56/5 (15 votes)
1 Aug 2020CPOL5 min read 91.2K  
How to use JSON in an ASP.NET application over a REST service using WebApi
In this post, you will see a basic example of how to successfully consume and use JSON in our ASP.NET application over a REST service using WebApi.

In my last post, I indicated how Microsoft & MS technologies have made programming for the web simple and easy. I also suggested how these same MS technologies have created misinformed web developers (like me) as well.

All the abstraction over the RESTful nature of HTML (or HTTP) have solved at least one purpose. They have managed to “abstract” a large number of developers from the inner workings of HTML or for that matter, the HTTP/web. Well, I would say making an Intranet business Application using ASP.NET does not necessarily require you to have any knowledge regarding JSON or the RESTful nature of Web for that matter. Using Web forms and WCF, you could easily create a Service Oriented Application without much knowledge of how the web actually works. But if you just dive in a bit deeper, you’ll get to know how WCF has its own quirks.

Ok, enough of “MS bashing” and “Developer belittling”. Learning the ropes of JSON is not that tough, I would say.

Ironically, with the recent emphasis MS has laid on introducing Open source packages into our VS projects, it has become easier to learn things like JSON and programming in HTML as it should be(RESTful) using things like ASP.NET webapi.

Let's get over that block in our head and quickly create a running JSON example (using Visual Studio of course ;) :P

Before we begin, it would be great to have some background.

So, What is JSON?

It's short for JavaScript Object Notation. In theory, we can describe CLR object as an equivalent Object in JavaScript. As you know, JavaScript is not a strictly object oriented language, BUT it has some features of OOP language.

Why is JSON Popular?

So, folks using WCF should know that the data transferred and consumed in a web application is usually in the form of XML. That is, any CLR object could be easily represented as an equivalent XML document. JSON is quite similar but has a lot less characters when representing the same data. Hence it's lighter and faster across the wire. Also, it's very easy to consume JSON objects in HTML/JavaScript as they are actually JavaScript objects.

What Do We Mean by RESTful Nature of Web?

REST stands for Representational State Transfer. What it says is that any request in/over HTTP should be one of the following types:

  • GET – Get a resource from a server
  • POST – Post/Insert/Input some information on a server
  • PUT – Update some information on a server
  • DELETE – Delete some information on a server

These are the standard “verbs” (along with a few others) supported by HTTP protocol.

This is where ASP.NET MVC WebApi comes into the picture. It helps us create a Web service on the paradigms of REST. It's similar to WCF with the difference that an ASP.NET WebApi service is usually consumed by a Client (browser) and we have more control as to what format (XML/JSON) flows through the wire.

Enough of theory, let's get to the Hands On!

  1. Open File –>New Project and select ASP.NET MVC 4 –> Internet template

    image

  2. Add a new New Class to the Models folder of your solution as below:
    C#
    public class Person
    {
    public string Name { get; set; }
        public int Age { get; set; }
        public string Sex { get; set; }
    }

    This is the class which we’ll be serializing and consuming in JavaScript.

  3. Right click on Controllers folder and Add a new Controller. Select Empty API Controller from the dropdown options as shown below:

    image

  4. Add a new method returning IEnumerable to the PersonApiController just added. Our objective is to send over a list of persons from the server and consume it via JSON in JavaScript.
    C#
    public class PersonApiController : ApiController
        {
    
    [HttpGet]
    public IEnumerable Get()
    {
    List lstPerson = new List() {
    new Person(){Name="Rahul",Age=28, Sex="M"},
    new Person(){Name="Chinmoy", Age = 28, Sex="M"},
    new Person(){Name="Charu",Age = 27, Sex="F"}
    };
    
    return lstPerson;
    }
    }

    Just one more thing. Since it's a RESTful service, we need to decorate our function with one of the HTTP verbs. In this case, we’ll use [HttpGet].

    We are now done with the server side implementation. Now onto the client side of things.

  5. Open up Index.chstml in the Home Views Folder and add the following markup at the end of the page. What we are doing here is we are placing a button on whose click we’ll make a call to get a list of people. Upon successful completion, we are going to display the details in a table.
    HTML
    @Scripts.Render("~/bundles/jquery")
    
    <input type="button" id="btnGetPeople" value="Get People">
    <div id="divPeople">
    <table>
    <thead>
    <tr>
    <th>Name</th>
    <th>Age</th>
    <th>Sex</th>
    </tr>
    </thead>
    <tbody id="tBody">
    </tbody>
    </table>
    </div>
    <script type="text/javascript">
    var AllPeople;
    $(document).ready(function () {
    
    $("#btnGetPeople").click(function () {
    //Do an AJAx Call here
    $.getJSON(‘@Url.Action("PersonApi", "api")’)
    .done(function (data) {
    // On success, ‘data’ contains a list of Person.
    AllPeople = data;
    
    for (var i = 0; i < AllPeople.length; i++) {
    $("tBody").append(‘
    ‘ + AllPeople[i].Name + ‘ ‘ + AllPeople[i].Age + ‘ ‘ + AllPeople[i].Sex + ");
    };
    });
    
    });
    
    });
    </script>

So what does the above code do?

  • It creates markup for a button and an empty HTML table
  • It declares a JavaScript variable AllPeople for storing the returned list of people. As you can see, JavaScript supports implicit variable declaration.
  • It makes a call to our PersonApi controller using a jQuery method called $.getJSON(). It's this call that does all the magic.

The ASP.NET MVC WebApi is intelligent enough to identify the format in which data is requested. Here, we are requesting JSON so the WebApi Controller action returns JSON; If we request XML, it will happily return XML.

  • Now, once the web service call is “done”, we iterate through our JSON object and populate our table as shown below:

image

Once you click the “Get People” button and if you place a debugger and see how the AllPeople variable looks like once populated by the returned “data”, it looks like below:

image

It's like any other array which we can iterate over.

The final result is as under:

image

We have successfully consumed and used JSON in our ASP.NET application over a REST service using WebApi. That’s how easy it is folks!

Of course, this was one of the most basic examples I could come up with, BUT hey, you gotta start somewhere (if you haven’t already started).

WebApi is cool! JSON is great! (WebApi + JSON) = Awesome !!

If you are creating for the web and are not using these technologies, I would suggest you start being awesome right away.

Building, consuming and deploying WebApi services has a few Gotchas, which I’ll discuss in a future blog post.

Do post your views/comments/feedback/questions below. I’ll try my best to answer them.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)