Join Dotnetcodes DotnetCodes.com is online Discussion Forum for Software professionals . It lets you find friends around the world and Create professional network that share similar interests as you. Get help on ur projects by industry specialists. Also get answers to all ur technical/placement related querries.Get an edge over others.
Already MemberClick here to login
ASP.net MVC Interview Questions Answers Interview Questions
Get Started Developing for Android Apps with Eclipse Articles
Whats New in ASP.NET 4.0 Part 2 Articles
.Net framework 4.0 Interview Questions Answers Interview Questions
SQL server reporting services Interview Questions (SSRS) part 1 Articles
SharePoint 2010 interview Questions Answers Interview Questions
Html5 interview questions and answers Interview Questions
Serial Number in SSRS Articles
How to Print a Crystal Report direct to printer Articles
Explaining SDLC -System Development Life Cycle Articles
Populate or bind Dropdownlist in Asp.net using Jquery and Json Articles
Sql Server Database Backup and Restore through C# Source Codes
ASP .Net Page Life cycle Articles
Benefits of Generics in .net Articles
Difference between Encapsulation and Abstraction Interview Questions
Submit Articles | More Articles..

Learn How to create ASP.NET Web API

Posted By: rakesh On:12/18/2013 11:04:03 PM in:Articles Category:ASP.NET MVC Hits:1934
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.

Introduction

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.

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 Web Application. Name the project "ProductsApp" and click OK.

In the New ASP.NET Project dialog, select the Empty template. Under "Add folders and core references for", check Web API. 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". Add the following properties to the Product class.

namespace ProductsApp.Models
{
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Category { get; set; }
        public decimal Price { get; set; }
    }
}

Adding a Controller

In Web API, a controller is an object that handles HTTP requests. We'll add a controller that can return either a list of products or a single product specified by ID.

In Solution Explorer, right-click the the Controllers folder. Select Add and then select Controller.

In the Add Scaffold dialog, select Web API Controller - Empty. Click Add.

In the Add Controller dialog, name the controller "ProductsController". Click Add.

The scaffolding creates a file named ProductsController.cs in the Controllers folder.

If this file is not open already, double-click the file to open it. Replace the code in this file with the following:

using ProductsApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web.Http;

namespace ProductsApp.Controllers
{
    public class ProductsController : ApiController
    {
        Product[] products = new Product[] 
        { 
            new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 }, 
            new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M }, 
            new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M } 
        };

        public IEnumerable<Product> GetAllProducts()
        {
            return products;
        }

        public IHttpActionResult GetProduct(int id)
        {
            var product = products.FirstOrDefault((p) => p.Id == id);
            if (product == null)
            {
                return NotFound();
            }
            return Ok(product);
        }
}

To keep the example simple, products are stored in a fixed array inside the controller class. Of course, in a real application, you would query a database or use some other external data source.

The controller defines two methods that return products:

  • The GetAllProducts method returns the entire list of products as an IEnumerable<Product> type.
  • The  GetProductById method looks up a single product by its ID.

That's it! You have a working web API.  Each method on the controller corresponds to one or more URIs:

For the GetProductByID method, the id in the URI is a placeholder. For example, to get the product with ID of 5, the URI is api/products/5.

In next article you can learn how to call WEB API with  JavaScript and jQuery

comments powered by Disqus
User Profile
Rakesh Sinha
Team Lead
Delhi , INDIA
Email :You must Log In to access the contact details.
Latest Post from :rakesh
How to Calculate sum of a column in a dataset
View: 270 | Submitted on: 9/17/2014 6:48:19 AM
ASP.NET MVC 4 Interview Questions and Answers
View: 447 | Submitted on: 9/1/2014 10:10:25 PM
What New in ASP.NET MVC 5
View: 823 | Submitted on: 6/6/2014 12:52:30 AM
What is view state in .Net?
View: 957 | Submitted on: 4/21/2014 9:44:52 PM
Rename database in sql server
View: 360 | Submitted on: 2/6/2014 9:57:16 PM
Submit Articles | All Post of This User..

All rights reserved to dotnetcodes. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks.
Best viewed at 1024 x 768 resolution with Internet Explorer 5.0 or Mozila Firefox 3.5 or Google Crome and higher