9. ASP.NET RESTful Web API

About this Tutorial

Objectives

Delegates will learn to develop web applications using C# 4.0. After completing this course, delegates will be able to:

  • Use Visual Studio 2012 effectively
  • Create commercial ASP.NET Web Applications
  • Develop user interfaces using Master Pages, Site Navigation and Themes

Audience

This course has been designed primarily for programmers new to the .Net development platform. Delegates experience solely in Windows application development or earlier versions of ASP.Net will also find the content beneficial.

Prerequisites

No previous experience in ASP.NET programming is required. But any experience you do have in programming will help. Also no experience in visual studio is required. But again any experience you do have with programming development environments will be a valuable.

Download Solutions

HTML tutorial


Overview

Estimated Time – 1 Hour

What is REST?

  • REST – Representational State Transfer.
  • “Intended to evoke an image of how a well-designed Web application behaves: a network of Web pages forms a virtual state machine, allowing a user to progress through the application by selecting a link or submitting a short data-entry form, with each action resulting in a transition to the next state of the application by transferring a representation of that state to the user.” Fielding & Taylor 2002

What is a RESTful Service?

  • RESTful services are resource-centric services.
  • Endpoints (URIs) represent resources.
  • Endpoints are accessible via standard HTTP.
  • Endpoints can be represented in a variety of formats (e.g. XML, JSON, HTML, plain text).
  • So a RESTful application access raw data from services via HTTP – a new twist on an old story!

RESTful services use HTTP verbs to define CRUD-style operations on resources –

CRUD

RESTful services return data, and set a response code to indicate the outcome, here are some HTTP response codes

Response

The easiest way to understand RESTful services is through an example, so imagine a hypothetical company that sells many different parts to many customers.
The company wants to provide services that:

  • Get a list of parts.
  • Get detailed part information.
  • Submit purchase orders (PO).

Example – Getting a Part List

  • The list of parts available from the company is a resource.
  • A resource is identified via a URI.
  • Resource representations are available via HTTP GET e.g. “GET https://www.acme.com/parts HTTP/1.1″
    will get a representation of the “list of parts” resource.
  • The list is an XML document.

    <?xml version="1.0"?>
    <p:Parts xmlns:p="https://www.acme.com" xmlns:xl="https://www.w3.org/1999/xlink">
    <Part id="0345" xl:href="https://www.acme.com/parts/0345"/>
    <Part id="0346" xl:href="https://www.acme.com/parts/0346"/>
    <Part id="0347" xl:href="https://www.acme.com/parts/0347"/>
    <Part id="0348" xl:href="https://www.acme.com/parts/0348"/>
    </p:Parts>

Example – Getting Part Info

  • Detailed part info is also a resource identified with a URL.
  • Getting detailed information: “GET https://www.acme.com/parts/0346 HTTP/1.1” will get a representation of a specific part.

    <?xml version="1.0"?>
    <p:Part xmlns:p="https://www.acme.com" xmlns:xl="https://www.w3.org/1999/xlink">
    <Part-ID>0346</Part-ID>
    <Name>Widget-A</Name>
    <Desc>This part is used in the pilot's cabin</Desc>
    <Spec xl:href="https://www.acme.com/parts/0346/spec"/>
    <UnitCost currency="USD">0.10</UnitCost>
    </p:Part>

Example – Submitting a PO

  • To order a part, the client submits a purchase order (PO).
  • The PO is also an XML document.
  • The PO is submitted using standard HTTP POST.
  • The Web service returns a URI for the submitted PO.

    <?xml version="1.0"?>
    <p:Order xmlns:p="https://www.acme.com" xmlns:xl="https://www.w3.org/1999/xlink">
    <Part xl:href="https://www.acme.com/parts/0346"/>
    <Quantity>10</Quantity>
    <Date>2013-10-11</Date>
    ...
    </p:Order>

Lab 1: Getting Started With the Web API

Lab 1: Getting Started With the Web API

Overview
What is the Web API?

  • A framework for creating and consuming RESTful services.
  • Via a new project template, “Web API”.

The Web API is based on familiar MVC principles, but it is not part of ASP.NET MVC

  • Microsoft has taken key classes and characteristics from the System.Web.Mvc namespace …
  • … and duplicated them in the System.Web.Http namespace

Differences between the Web API and MVC
In the Web API:

  • Controller classes inherits from ApiController.
  • Action methods correspond to resource requests, e.g. Get…(), Post…(), Put…(), Delete…().
  • Action methods return data (“resources”), rather than views.
  • Data is serialized back to the user in an appropriate format, e.g. JSON, XML, etc –
  • This is based on the accept header sent in the browser HTTP request.
    1. We will create a simple application to demonstrate REST. To start, open Visual Studio 2012>New Project>C#>ASP.NET MVC4 and in the Project template window choose Web API using the Razor engine, call this HelloWebApi.

Web

    1. The Web API project will initially contain two controller classes, Rename ValuesController to ProductsController.

      • HomeController – A traditional MVC controller, for serving up views.
      • ProductsController – A RESTful MVC controller, for serving up resources.
    2. To the solution add a Class to the Models folder called Product and use this code to hold the values for the id and the name

      public class Product
      {
      public int Id { get; set; }
      public String Name { get; set; }
      }
    3. In ProductsController add this array of products just below the class; this is used for when we want to return the information to the user.

      Product[] products = new Product[]
      {
      new Product { Id = 1, Name = "HTML Course"},
      new Product { Id = 2, Name = "C# Course"},
      new Product { Id = 3, Name = "VB Course"}
      };
    4. Change the methods in the ProductsController. These methods are called via the routing system, but unlike standard MVC correspond to verbs in the HTTP message. Unlike standard MVC they return raw data to the browser, not a view.

      public class ProductsController : ApiController
      .....
      // GET api/values/5
      public string Get(int id)
      {
      return "Here's value " + id;
      }
      public IEnumerable<Product> GetAllProducts()
      {
      return products;
      }
      // POST api/values
      public void Post([FromBody]string value)
      {
      }
      // PUT api/values/5
      public void Put(int id, [FromBody]string value)
      {
      }
      // DELETE api/values/5
      public void Delete(int id)
      {
      }
    5. The next step is in the View Index remove all current html and replace with

      <script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")"
      type="text/javascript"></script>
      <script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"
      type="text/javascript"></script>
      <html>
      <head>
      <title>Product App</title>
      </head>
      <body>
      <div>
      <h2>All Products</h2>
      <ul id="products" />
      </div>
      </body>
      @section scripts{
      <script type="text/javascript">
      $(document).ready(function () {
      // Send an AJAX request
      $.getJSON('api/Products')
      .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;
      }
      </script>
      }
      </html>
    6. The HTML and javascript above will create a very basic webapage that will have Products at the top and a list beneath this. The list will be filled on loading of the page using javascript that receives the JSON and will then in &lt:li> will add the name of the item

Website

  1. To invoke a RESTful Service Operation:

    • Run the project and enter these URLs in the browser:
    • https://localhost:55538/api/Products – Sends an HTTP GET request to the Web app, MVC routes the request to ProductsController this invokes the Get() action method and the method “gets” a collection of strings, which is serialized back to the browser in an appropriate format (e.g. JSON, XML, etc.).
    • https://localhost:55538/api/Products/5 – Same idea, this time it invokes the Get(int id) action method and the method “gets” a single string, which is serialized as above.

Lab 2: Understanding Web API Routing

Lab 2: Understanding Web API Routing
    1. This is default web API routing, found in Application_start in Global.asax.cs. It is similar to normal MVC routing.

      protected void Application_Start()
      {
      WebApiConfig.Register(GlobalConfiguration.Configuration);
      ...
      }
    2. WebApiConfig.Register() registers a default entry in the Web API routing table, found under App_start/WebApiConfig.cs.

      public static class WebApiConfig
      public static void Register(HttpConfiguration config)
      {
      config.Routes.MapHttpRoute(
      name: "DefaultApi",
      routeTemplate: "api/{controller}/{id}",
      defaults: new { id = RouteParameter.Optional }
      );
      }
      }

Explain

  1. The routeTemplate property in the route entry identifies which controller to use.

    config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
    );
  2. Here’s a Web API controller class for Product resources using default action method names.

    public class ProductsController : ApiController
    {
    // GET api/products
    public IEnumerable<Product> GetAllProducts() {...}
    // GET api/products/5
    public Product GetProductById(int id) {...}
    // GET api/products?category=Beverage
    public IEnumerable<Product> GetProductsInCategory(string category) {...}
    // POST api/products
    public void PostProduct([FromBody]Product prod) {...}
    // PUT api/products/5
    public void PutProduct(int id, [FromBody]Product prod) {...}
    // DELETE api/products/5
    public void DeleteProduct(int id) {...}
    }
  3. Now for the annotated action methods using System.Web.Http.

    using System.Web.Http;
    ...
    public class ProductsController : ApiController
    {
    // GET api/products
    [HttpGet]
    public IEnumerable<Product> AllProducts() {...}
    // GET api/products/5
    [HttpGet]
    public Product ProductById(int id) {...}
    // GET api/products?category=Beverage
    [HttpGet]
    public IEnumerable<Product> ProductsInCategory(string category) {...}
    // POST api/products
    [HttpPost]
    public void CreateProduct([FromBody]Product prod) {...}
    // PUT api/products/5
    [HttpPut]
    public void UpdateProduct(int id, [FromBody]Product prod) {...}
    // DELETE api/products/5
    [HttpDelete]
    public void DeleteProduct(int id) {...}
    }
Well done!. You have completed the MVC course
How do I get a certificate of Completion for this course?
  1. Once you have subscribed, TalkIT can monitor some of your activity on the website. But as the tutorials are designed to allow you to work when you want, we do not know exactly when you have finished a course – So just email TalkIT with:
    • The date you have completed all the tutorials in the course
    • Include the title of the course
  2. TalkIT will then send you a certificate of completion for that course

 

Back to beginning
Copyright © 2016 TalkIT®






If you liked this post, please comment with your suggestions to help others.
If you would like to see more content like this in the future, please fill-in our quick survey.
Scroll to Top