"
ASP.NET (snapshot 2017) Microsoft documentation and samples

Using Web API with ASP.NET Web Forms

by Mike Wasson

Although ASP.NET Web API is packaged with ASP.NET MVC, it is easy to add Web API to a traditional ASP.NET Web Forms application. This tutorial walks you through the steps.

Overview

To use Web API in a Web Forms application, there are two main steps:

Create a Web Forms 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 Web Forms Application. Enter a name for the project and click OK.

Create the Model and Controller

This tutorial uses the same model and controller classes as the Getting Started tutorial.

First, add a model class. In Solution Explorer, right-click the project and select Add Class. Name the class Product, and add the following implementation:

[!code-csharpMain]

   1:  public class Product
   2:  {
   3:      public int Id { get; set; }
   4:      public string Name { get; set; }
   5:      public decimal Price { get; set; }
   6:      public string Category { get; set; }
   7:  }

Next, add a Web API controller to the project., A controller is the object that handles HTTP requests for Web API.

In Solution Explorer, right-click the project. Select Add New Item.

Under Installed Templates, expand Visual C# and select Web. Then, from the list of templates, select Web API Controller Class. Name the controller “ProductsController” and click Add.

The Add New Item wizard will create a file named ProductsController.cs. Delete the methods that the wizard included and add the following methods:

[!code-csharpMain]

   1:  namespace WebForms
   2:  {
   3:      using System;
   4:      using System.Collections.Generic;
   5:      using System.Linq;
   6:      using System.Net;
   7:      using System.Net.Http;
   8:      using System.Web.Http;
   9:   
  10:      public class ProductsController : ApiController
  11:      {
  12:   
  13:          Product[] products = new Product[] 
  14:          { 
  15:              new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 }, 
  16:              new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M }, 
  17:              new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M } 
  18:          };
  19:   
  20:          public IEnumerable<Product> GetAllProducts()
  21:          {
  22:              return products;
  23:          }
  24:   
  25:          public Product GetProductById(int id)
  26:          {
  27:              var product = products.FirstOrDefault((p) => p.Id == id);
  28:              if (product == null)
  29:              {
  30:                  throw new HttpResponseException(HttpStatusCode.NotFound);
  31:              }
  32:              return product;
  33:          }
  34:   
  35:          public IEnumerable<Product> GetProductsByCategory(string category)
  36:          {
  37:              return products.Where(
  38:                  (p) => string.Equals(p.Category, category,
  39:                      StringComparison.OrdinalIgnoreCase));
  40:          }
  41:      }
  42:  }

For more information about the code in this controller, see the Getting Started tutorial.

Add Routing Information

Next, we’ll add a URI route so that URIs of the form “/api/products/” are routed to the controller.

In Solution Explorer, double-click Global.asax to open the code-behind file Global.asax.cs. Add the following using statement.

[!code-csharpMain]

   1:  using System.Web.Http;

Then add the following code to the Application_Start method:

[!code-csharpMain]

   1:  RouteTable.Routes.MapHttpRoute(
   2:      name: "DefaultApi",
   3:      routeTemplate: "api/{controller}/{id}",
   4:      defaults: new { id = System.Web.Http.RouteParameter.Optional }
   5:  );

For more information about routing tables, see Routing in ASP.NET Web API.

Add Client-Side AJAX

That’s all you need to create a web API that clients can access. Now let’s add an HTML page that uses jQuery to call the API.

Make sure your master page (for example, Site.Master) includes a ContentPlaceHolder with ID="HeadContent":

[!code-htmlMain]

   1:  <asp:ContentPlaceHolder runat="server" ID="HeadContent"></asp:ContentPlaceHolder>

Open the file Default.aspx. Replace the boilerplate text that is in the main content section, as shown:

[!code-aspxMain]

   1:  <%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" 
   2:      AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebForms._Default" %>
   3:   
   4:  <asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
   5:  </asp:Content>
   6:   
   7:  <asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
   8:      <h2>Products</h2>
   9:      <table>
  10:      <thead>
  11:          <tr><th>Name</th><th>Price</th></tr>
  12:      </thead>
  13:      <tbody id="products">
  14:      </tbody>
  15:      </table>
  16:  </asp:Content>

Next, add a reference to the jQuery source file in the HeaderContent section:

[!code-aspxMain]

   1:  <asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
   2:      <script src="Scripts/jquery-1.10.2.min.js" type="text/javascript"></script>
   3:  </asp:Content>

Note: You can easily add the script reference by dragging and dropping the file from Solution Explorer into the code editor window.

Below the jQuery script tag, add the following script block:

[!code-htmlMain]

   1:  <script type="text/javascript">
   2:      function getProducts() {
   3:          $.getJSON("api/products",
   4:              function (data) {
   5:                  $('#products').empty(); // Clear the table body.
   6:   
   7:                  // Loop through the list of products.
   8:                  $.each(data, function (key, val) {
   9:                      // Add a table row for the product.
  10:                      var row = '<td>' + val.Name + '</td><td>' + val.Price + '</td>';
  11:                      $('<tr/>', { html: row })  // Append the name.
  12:                          .appendTo($('#products'));
  13:                  });
  14:              });
  15:          }
  16:   
  17:          $(document).ready(getProducts);
  18:  </script>

When the document loads, this script makes an AJAX request to “api/products”. The request returns a list of products in JSON format. The script adds the product information to the HTML table.

When you run the application, it should look like this:



Comments ( )
Link to this page: //www.vb-net.com/AspNet-DocAndSamples-2017/aspnet/web-api/overview/getting-started-with-aspnet-web-api/using-web-api-with-aspnet-web-forms.htm
< THANKS ME>