Introduction: Visual
Studio 2012 and .Net 4.5 comes with a new web services framework called the ASP.NET Web API. It is designed to simplify
the development and consumption of RESTful
service.
This sample uses MVC 4 ASP.NET Web API to build a simple Book API application
to display a list of books.
Steps:
Create a Web API Project
Start Visual Studio and select New Project from the Start page. Or, from the File menu, select New and then Project. In the Templates pane, select Installed Templates and
expand the Visual C# node. Under Visual C#, select Web. In the list of project
templates, select ASP.NET MVC 4 Web Application. Name
the project "bookAPI" and click OK.
In the New ASP.NET
MVC 4 Project dialog, select the “WebAPI” template.
Add a Model
A model is
an object that represents the data in your application. ASP.NET Web API can
automatically serialize your model to JSON, XML, or some other format, and then
write the serialized data into the body of the HTTP response message. As long
as a client can read the serialization format, it can deserialize the object.
Most clients can parse either XML or JSON. Moreover, the client can indicate
which format it wants by setting the Accept header in the HTTP request message.
We’ll create a simple model that represents a book.
If Solution Explorer is not
already visible, click the View menu
and select Solution Explorer. In Solution
Explorer, right-click the Models folder. From the context menu, select Add then select Class. Name the class "Book". Add the following
properties to the
Book
class.
namespace bookApi.Models
{
public class Book
{
public int Id { get; set; }
public string Title { get; set; }
public string Author { get; set; }
public decimal Price { get; set; }
}
}
Add a Controller
In Web API, a controller is
an object that handles HTTP requests. The controller will display a list of
books.
In Solution Explorer, right-click the the Controllers folder. Select Add and
then select Controller.
In the “Add
Controller” dialog select “Empty API
Controller”. Click Add.
In the Add Controller dialog,
name the controller "BookController". Click Add.
Open BookController.cs and replace the code with the
following code:
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Net;
using
System.Net.Http;
using
System.Web.Http;
using
bookApi.Models;
namespace
bookApi.Controllers
{
public
class
BookController : ApiController
{
Book[]
books = new Book[]
{
new
Book { Id = 1, Title = "Dark Witch", Author = "Nora Roberts", Price = 9 } ,
new
Book { Id = 2, Title = "Fifty Shades Of Grey", Author = "E.L.James", Price = 8 },
new
Book { Id = 2, Title = "The Harbinger", Author = "Jonathan Cahn", Price = 10}
};
public
IEnumerable<Book>
GetAllBooks()
{
return
books;
}
}
}
Test the Output:
Press ctrl
+ f5 and then append api/book with your URL. It should look like http://localhost:yourportNumber/api/book. It will ask if you want to open or save “book.Json”
from localhost. Open and you should see the following output:
Output:
[{"Id":1,"Title":"Dark
Witch","Author":"Nora Roberts","Price":9.0},{"Id":2,"Title":"Fifty
Shades Of
Grey","Author":"E.L.James","Price":8.0},{"Id":2,"Title":"The
Harbinger","Author":"Jonathan
Cahn","Price":10.0}]
Call the Web API with Javascript and jQuery
We'll add a HTML page that uses AJAX to call the web API.
In Solution Explorer, right-click the project and
select Add, then select New Item.
In the Add New Item dialog,
select the Web node
under Visual C#, and then select the HTML Page item.
Name the page "default.html".
Replace
code with the following code:
--default,html
<!DOCTYPE
html>
<html
xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Product
App</title>
</head>
<body>
<div>
<h2>All
Books</h2>
<ul
id="books"
/>
</div>
<script
src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
<script>
var
uri = 'api/book';
$(document).ready(function
() {
// Send an AJAX
request
$.getJSON(uri)
.done(function
(data) {
//
On success, 'data' contains a list of books.
$.each(data, function
(key, item) {
//
Add a list item for the book.
$('<li>',
{ text: formatItem(item) }).appendTo($('#books'));
});
});
});
function
formatItem(item) {
return
"id:" + item.Id + " Author : "
+ item.Author + " Title: "
+ item.Title + " Price: $" + item.Price;
}
</script>
</body>
</html>
Run the Application
Press cntl+f5 and then append default.html as http://localhost:portnumner/default.html
and it should
look like the following :
No comments:
Post a Comment