Click here to Skip to main content
11,636,300 members (77,647 online)
Click here to Skip to main content

Tagged as

JSON and RESTful Web services using ASP.NET MVC WebApi–Its what every Web Programmer should know !

, 17 Jul 2014 CPOL 25.1K 9
Rate this:
Please Sign up or sign in to vote.
In my last post I indicated as to 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

In my last post I indicated as to 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.

Lets get over that block in our head and quickly create a running JSON example (using Visual Studio of courseWinking smileSmile with tongue out)

Before Starting, it would be great to have some background.

So, What is JSON?

Its 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 its lighter and faster across the wire. Also, its 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 picture. It helps us create a Web service on the paradigms of REST. Its 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, Lets 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 :

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.

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

@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(&lsquo;@Url.Action("PersonApi", "api")&rsquo;)
.done(function (data) {
// On success, &lsquo;data&rsquo; contains a list of Person.
AllPeople = data;

for (var i = 0; i < AllPeople.length; i++) {
$("tBody").append(&lsquo;
&lsquo; + AllPeople[i].Name + &lsquo; &lsquo; + AllPeople[i].Age + &lsquo; &lsquo; + 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(). Its 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

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

The post JSON and RESTful Web services using ASP.NET MVC WebApi–Its what every Web Programmer should know ! appeared first on Chinmoy Mohanty's Blog.

License

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

Share

About the Author

Chinmoy Mohanty
Software Developer
India India
I am a Developer working across .NET Technologies.
Passionate about WEB technologies more than anything.
Fascinated about the idea of how the WEB world and the WinForm world are slowly merging into each other, with a very thin line to differentiate them.

I am an active blogger and I blog mostly about Technology. Also, I have presented at certain points in the past on technical topics.

My Blog

Life & Tech

Programming Community Profiles

Stack Overflow

Presentations

Slideshare

Social Profiles

Facebook | Twitter | LinkedIn | Google+

You may also be interested in...

Comments and Discussions

 
QuestionArticle Pin
jokerman8-Mar-15 0:21
memberjokerman8-Mar-15 0:21 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.150728.1 | Last Updated 17 Jul 2014
Article Copyright 2014 by Chinmoy Mohanty
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid