Tuesday, November 27, 2012

Your First ASP.NET Web API (C#) - I


HTTP is not just for serving up web pages. It is also a powerful platform for building APIs that expose services and data. HTTP is simple, flexible, and ubiquitous. Almost any platform that you can think of has an HTTP library, so HTTP services can reach a broad range of clients, including browsers, mobile devices, and traditional desktop applications.
ASP.NET Web API is a framework for building web APIs on top of the .NET Framework. In this tutorial, you will use ASP.NET Web API to create a web API that returns a list of products. The front-end web page uses jQuery to display the results.
This tutorial requires Visual Studio with ASP.NET MVC 4. You can use any of the following:
  • Visual Studio 2012
  • Visual Studio Express 2012 for Web
  • Visual Studio 2010 with ASP.NET MVC 4 installed.
  • Visual Web Developer 2010 Express with ASP.NET MVC 4 installed.
If you are using Visual Studio 2010 or Visual Web Developer 2010 Express, you will need to install ASP.NET MVC 4 separately. The screenshots in this tutorial show Visual Studio Express 2012 for Web.

Create a Web API Project

Start Visual Studio and select New Project from the Start page. Or, from the File menu, select New and thenProject.
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 "HelloWebAPI" and clickOK.
In the New ASP.NET MVC 4 Project dialog, select Web API and click OK.

Adding a Model

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.
Let's start by creating a simple model that represents a product.
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 "Product". Next, add the following properties to the Product class.
namespace HelloWebAPI.Models
{
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Category { get; set; }
        public decimal Price { get; set; }
    }
}



No comments:

Post a Comment