In ASP.NET Web API, a controller is a class that handles HTTP requests. The public methods of the controller are called action methods or simply actions. When the Web API framework receives a request, it routes the request to an action.
Introduction
This article shows the walk through of how to add routing information to a WEB API which routes HTTP requests to controllers
Objective
The Objective of this article is to explain how to add routing information
Before we start please have a look at
Part 5 article as this was the continuation of it.
Now open Global.asax from the solution which we had created earlier
Add the below code
using System;
using System.Web;
using System.Web.Routing;
using System.Web.Http;
namespace WebAPIforms
{
public class Global : HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
RouteTable.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = System.Web.Http.RouteParameter.Optional }
);
}
}
}
Now let's add an HTML page that uses jQuery to call the API.
<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebAPIforms._Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<script src="Scripts/jquery-1.8.2.js"></script>
<script type="text/javascript">
function getStudents() {
$.getJSON("api/Students",
function (data) {
$('#Students').empty(); // Clear the table body.
// Loop through the list of Students.
$.each(data, function (key, val) {
// Add a table row for the Student.
var row = '<td>' + val.Name + '</td> <td>' + val.Marks + '</td>';
$('<tr/>', { text: row }) // Append the name.
.appendTo($('#Students'));
});
});
}
$(document).ready(getStudents);
</script>
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<h2>Students</h2>
<table>
<thead>
<tr><th>Name</th><th> Marks</th></tr>
</thead>
<tbody id="Students">
</tbody>
</table>
</asp:Content>
The script makes an AJAX request to "api/Students". The request returns a list of Students in JSON format. The script adds the Student information to the HTML table.