Quantcast
Channel: Effect Labs Blog - WCF RIA
Viewing all articles
Browse latest Browse all 2

Start a Web API - ASP.NET MVC Web API

$
0
0

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

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; }

    }

}

Adding a Controller

controller is an object that handles HTTP requests. The New Project wizard created two controllers for you when it created the project. To see them, expand the Controllers folder in Solution Explorer.

·         HomeController is a traditional ASP.NET MVC controller. It is responsible for serving HTML pages for the site, and is not directly related to Web API.

·         ValuesController is an example WebAPI controller.

Go ahead and delete ValuesController, by right-clicking the file in Solution Explorer and selecting Delete.

Add a new controller, as follows:
In Solution Explorer, right-click the the Controllers folder. Select Add and then select Controller

 

In the Add Controller wizard, name the controller "ProductsController". In the Template drop-down list, selectEmpty API Controller. Then click Add.

The Add Controller wizard will create 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 HelloWebAPI.Models;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Web.Http;

 

namespace HelloWepAPI.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 Product GetProductById(int id)

        {

            var product = products.FirstOrDefault((p) => p.Id == id);

            if (product == null)

            {

                throw new HttpResponseException(HttpStatusCode.NotFound);

            }

            return 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 maps to a URI:

Controller Method

URI

GetAllProducts

/api/products

GetProductById

/api/products/id

A client can invoke the method by sending an HTTP GET request to the URI. Later, we'll look at how this mapping is done. But first, let's try it out.

Calling the Web API from the Browser

You can use any HTTP client to invoke your web API. In fact, you can call it directly from a web browser.

In Visual Studio, choose Start Debugging from the Debug menu, or use the F5 keyboard shortcut.  The ASP.NET Development Server will start, and a notification will appear in the bottom corner of the screen showing the port number that it is running under. By default, the Development Server chooses a random port number.

Visual Studio will then automatically open a browser window whose URL points to http//www.localhost:xxxx/, where xxxx is the port number. The home page should look like the following:

 

 

 

This home page is an ASP.NET MVC view, returned by the HomeController class.  To invoke the web API, we must use one of the URIs listed previously. For example, to get the list of all products, browse tohttp://localhost:xxxx/api/products/. (Replace "xxxx" with the actual port number.)

The exact result depends on which web browser you are using. Internet Explorer will prompt you to open or save a "file" named products.

This "file" is actually just the body of the HTTP response. Click Open. In the Open with dialog, select Notepad. Click OK, and when prompted, click Open. The file should contain a JSON representation of the array of products:

[{"Id":1,"Name":"Tomato soup","Category":"Groceries","Price":1.0},{"Id":2,"Name":

"Yo-yo","Category":"Toys","Price":3.75},{"Id":3,"Name":"Hammer","Category":

"Hardware","Price":16.99}]

 

Mozilla Firefox, on the other hand, will display the list as XML in the browser.


The reason for the difference is that Internet Explorer and Firefox send different Accept headers, so the web API sends different content types in the response.

Now try browsing to http://localhost:xxxx/api/products/1. This request should return the entry with ID equal to 1.

Calling the Web API with Javascript and jQuery

In the previous section, we invoked the web API directly from the browser. But most web APIs are meant to be consumed programmatically by a client application. So let's write a simple javascript client.

In Solution Explorer, expand the Views folder, and expand the Home folder under that. You should see a file named Index.cshtml. Double-click this file to open it.

Replace everything in this file with the following:

<div id="body">

    <section class="content-wrapper main-content clear-fix">

        <div>

            <h2>All Products</h2>

            <ul id="products" />

        </div>

        <div>

            <h2>Search by ID</h2>

            <input type="text" id="prodId" size="5" />

            <input type="button" value="Search" onclick="find();" />

            <p id="product" />

        </div>

    </section>

</div>

 

@section scripts {

<script>

    var apiUrl = 'api/products';

 

    $(document).ready(function () {

        // Send an AJAX request

        $.getJSON(apiUrl)

            .done(function (data) {

                // On success, 'data' contains a list of products.

                $.each(data, function (key, item) {

                    // Add a list item for the product.

                    $('<li>', { text: formatItem(item) }).appendTo($('#products'));

                });

            });

    });

 

    function formatItem(item) {

        return item.Name + ': $' + item.Price;

    }

 

    function find() {

        var id = $('#prodId').val();

        $.getJSON(apiUrl + '/' + id)

            .done(function (data) {

                $('#product').text(formatItem(data));

            })

            .fail(function (jqXHR, textStatus, err) {

                $('#product').text('Error: ' + err);

            });

    }

</script>

}

Getting a List of Products

To get a list of products, send an HTTP GET request to "/api/products".

The jQuery getJSON function sends an AJAX request. For response contains array of JSON objects. The donefunction specifies a callback that is called if the request succeeds. In the callback, we update the DOM with the product information.

$(document).ready(function () {

    // Send an AJAX request

    $.getJSON(apiUrl)

        .done(function (data) {

            // On success, 'data' contains a list of products.

            $.each(data, function (key, item) {

                // Add a list item for the product.

                $('<li>', { text: formatItem(item) }).appendTo($('#products'));

            });

        });

})

Getting a Product By ID

To get a product by ID, send an HTTP GET  request to "/api/products/id", where id is the product ID.

function find() {

        var id = $('#prodId').val();

        $.getJSON(apiUrl + '/' + id)

            .done(function (data) {

                $('#product').text(formatItem(data));

            })

            .fail(function (jqXHR, textStatus, err) {

                $('#product').text('Error: ' + err);

            });

    }

We still call getJSON to send the AJAX request, but this time we put the ID in the request URI. The response from this request is a JSON representation of a single product.

Running the Application

 

Press F5 to start debugging the application. The web page should look like the following:

Now you Can find the products by their Id as well, by entering their ID in Text field and click on search Button.
Stay tuned for further Informations.


Viewing all articles
Browse latest Browse all 2

Latest Images

Trending Articles





Latest Images