Creating Custom Asp.Net Web API using Handler .ASHX Also Example On Using It With JQuery And WebRequest

This blog post is about custom Asp.Net Web API and it is not like standard Web API using Web Api Controllers, Url routing etc.
I use general term or concept of Web API that is simply programming interface in a web. This can be done with many ways. Later on, the standard Microsoft Asp.Net Web API will be presented in this blog. API is just an additional layer in application usually to access data. Web API can be consumed by any device or method that support HTTP. With that concept, I use Handler .ASHX to make an Web API. This post shows custom Web API used by Client script with JQuery also by Asp.Net Server Control. I give those examples in below list. Steps for creating custom Web API using .ASHX:

    1. Create a Web Project
    2. Add new class as Model to represent data: (Persons.cs)
      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Web;
      
      public class Persons
      {
          List<Person> list;
      	public Persons()
      	{
              list = new List<Person>()
              {
                  new Person() { Id=1, FirstName="John", LastName="Doe", Department="A" },
                  new Person() { Id=2, FirstName="Jane", LastName="Voltus", Department="A"},
                  new Person() { Id=3, FirstName="Joseph", LastName="Chow", Department="B"}
              };
      
      	}
      
          public List<Person> getPersonList() {
              return list;
          }
      
          public void addPerson(Person p)
          {
              list.Add(p);
          }
      
          public void deletePerson(int Id)
          {
      		//code to delete
          }
          
      }
      
      public class Person
      {
          public int Id { get; set; }
          public string FirstName { get; set; }
          public string LastName { get; set; }
          public string Department { get; set; }
      }
      

      Off course you can change to use database connection and so on.

  1. Add new class, JSONHelper.cs Mostly Web API returns data with JSON format. This static class is needed to convert string to JSON. I got below class from asp.net – How to create JSON string in C# – Stack Overflow
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Script.Serialization;
    
    public static class JSONHelper
    {
        public static string ToJSON(this object obj)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            return serializer.Serialize(obj);
        }
    
        public static string ToJSON(this object obj, int recursionDepth)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            serializer.RecursionLimit = recursionDepth;
            return serializer.Serialize(obj);
        }
    }
    
  2. Add a Handler, PersonController.ashx. This will act like a web api controller. You can put it under your new folder, Controllers
    <%@ WebHandler Language="C#" Class="PersonController" Debug="true"%>
    
    using System;
    using System.Web;
    using System.Collections.Generic;
    using System.Web.SessionState;
    
    public class PersonController : IHttpHandler,IRequiresSessionState {
           
        public void ProcessRequest (HttpContext context) {
            context.Response.ContentType = "text/html";
           
            if (context.Application.Contents["Persons"] == null)
            {
                context.Application.Contents["Persons"] = new Persons();
            } 
            string action = context.Request.QueryString["action"];
            switch (action) {
                case "getPerson" :
                    getListPerson(context);
                    break;
                case "postPerson":
                    int _Id = Convert.ToInt32(context.Request.Form["Id"]);
                    string _FirstName = context.Request.Form["FirstName"];
                    string _LastName = context.Request.Form["LastName"];
                    string _Department = context.Request.Form["Department"];
                   
                    addPerson(context, _Id, _FirstName, _LastName, _Department);
                    context.Response.Write("OK");
                    break;
            }
        }
     
        public bool IsReusable {
            get {
                return false;
            }
        }
        
        
        private  void getListPerson(HttpContext context)
        {
           
            Persons prns = (Persons)context.Application.Contents["Persons"];
            List<Person> lstPrns = prns.getPersonList();
            string jsonString = "";
            if (lstPrns.Count > 0)
            {
                jsonString = lstPrns.ToJSON();
            }        
            
            context.Response.Write(jsonString);
        }
    
        private void addPerson(HttpContext context, int _Id, string _FirstName, string _LastName, string _Department)
        {
           
            Persons prns = (Persons)context.Application.Contents["Persons"];        
            prns.addPerson(new Person() { Id = _Id, FirstName = _FirstName, LastName = _LastName, Department = _Department });
           
            context.Application.Contents["Persons"] = prns;
        }
    
    }
    

    Above Ashx file contains handlers for user actions. It has getListPerson and addPerson procedure.

  3. Using web api controller with JQuery
    • Add Jquery script to your project jquery-1.6.2.min.js
    • Example of Using Ajax to get Person data and add record with client side script
      <%@ Page Language="C#" AutoEventWireup="true" CodeFile="JQueryClientHTMLElem.aspx.cs" Inherits="_Default" Debug="true" %>
      
      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
      
      <html xmlns="http://www.w3.org/1999/xhtml">
      <head runat="server">
          <title></title>
          <script src="Scripts/jquery-1.6.2.min.js" type="text/javascript"></script>
          <script type="text/javascript">
              function getList() {
                  $.ajax({
                      url: "Controlers/PersonController.ashx?action=getPerson",
                      type: "GET",
                      data: "",
                      dataType: "json",
                      success: function (data) {                    
                          var info = "List of Person:<br><table >";
                          $.each(data, function (key, val) {
                              info = info + "<tr><td>" + val.Id + "</td><td>" + val.FirstName + "</td>";
                              info = info + "<td>" + val.LastName + "</td><td>" + val.Department + "</td></tr>";
      
                          });
                          info = info + "</table>";
                          $("#lstPersons").html(info);
                      },
                      error: function () {
                          alert("The call to the web service failed.");
                      }
      
                  });
              }
      
              $(document).ready(function () {
                  getList();
      
                  $("#btnAdd").click(function () {
                      $.ajax({
                          url: "Controlers/PersonController.ashx?action=postPerson",
                          type: "POST",
                          data: $("#form1").serialize(),
                          success: function (response) {
                              if (response == "OK") {
                                  getList();
                              }
                          }
                      });
                  });
              });
      
              
          </script>
      </head>
      <body >
          <form id="form1">
          <div id="lstPersons"></div>
          <table>
              <tr>
              <td>Id</td><td><input type="text" id="Id" name="Id" size="3" /></td>
              </tr>
              <tr>
              <td>First Name</td><td><input type="text" id="FirstName" name="FirstName" /></td>
              </tr>
              <tr>
              <td>Last Name</td><td><input type="text" id="LastName" name="LastName" /></td>
              </tr>
              <tr>
              <td>Department</td><td><input type="text" id="Department" name="Department" /></td>
              </tr>
              <tr>
              <td colspan="2"><input type="button" id="btnAdd" value="ADD" /></td>
              </tr>
          </table>
          </form>
      </body>
      </html>
      

      By convention standard, HTTP Verb is used by Web API when users want to get and/or post data. Verb “GET” is to retrieve data, “POST” is to add new or update. Also Action which are GET, PUT, DELETE. Here I just made my own criteria, i.e action=getPerson, action=postPerson so that one specific action will do task for specific request. The result is the same. The difference is only how you code it.

  4. Using Web Api Controller by Server Control
    • Aspx file:
      <%@ Page Language="C#" AutoEventWireup="true" CodeFile="ServerControlWebRequest.aspx.cs" Inherits="ServerControlWebRequest" Debug="true" %>
      
      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
      
      <html xmlns="http://www.w3.org/1999/xhtml">
      <head runat="server">
          <title></title>
      </head>
      <body>
          <form id="form1" runat="server" >
          <div>
             
                  <asp:Label ID="lbltest" runat="server"></asp:Label>
              <asp:Table ID="tblPersons" runat="server">
                  <asp:TableHeaderRow>
                      <asp:TableHeaderCell>Id</asp:TableHeaderCell>
                      <asp:TableHeaderCell>First Name</asp:TableHeaderCell>
                      <asp:TableHeaderCell>Last Name</asp:TableHeaderCell>
                      <asp:TableHeaderCell>Department</asp:TableHeaderCell>
                  </asp:TableHeaderRow>
                  <asp:TableRow ID="rowContent">                
                  </asp:TableRow>
              </asp:Table>
      
      
              <asp:Table ID="tblinsert" runat="server">
                  <asp:TableRow>
                      <asp:TableCell><asp:Label ID="Label1" runat="server" Text="Id :" AssociatedControlID="Id"></asp:Label></asp:TableCell>
                      <asp:TableCell><asp:TextBox ID="Id" runat="server" Width="60"></asp:TextBox></asp:TableCell>
                  </asp:TableRow>
                  <asp:TableRow>
                      <asp:TableCell><asp:Label ID="Label2" runat="server" Text="First Name :" AssociatedControlID="FirstName"></asp:Label></asp:TableCell>
                      <asp:TableCell><asp:TextBox ID="FirstName" runat="server"></asp:TextBox></asp:TableCell>
                  </asp:TableRow>
                  <asp:TableRow>
                      <asp:TableCell><asp:Label ID="Label3" runat="server" Text="Last Name :" AssociatedControlID="LastName"></asp:Label></asp:TableCell>
                      <asp:TableCell><asp:TextBox ID="LastName" runat="server"></asp:TextBox></asp:TableCell>
                  </asp:TableRow>
                  <asp:TableRow>
                      <asp:TableCell><asp:Label ID="Label4" runat="server" Text="Department :" AssociatedControlID="Department"></asp:Label></asp:TableCell>
                      <asp:TableCell><asp:TextBox ID="Department" runat="server"></asp:TextBox></asp:TableCell>
                  </asp:TableRow>
                  <asp:TableRow>
                      <asp:TableCell ColumnSpan="2"><asp:Button ID="btnAdd" runat="server" Text="ADD" /></asp:TableCell>
                  </asp:TableRow>
              </asp:Table>
             
          </div>
          
          </form>
      </body>
      </html>
      

      No client script accessed web api controller. All used Server Control or server side script which means you also can access web api using winform control.

    • Behind code file WebRequest is used to browse Web Api Url and its response processed by WebResponse.
      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Web;
      using System.Web.UI;
      using System.Web.UI.WebControls;
      using System.Net;
      using System.IO;
      using System.Web.Script.Serialization;
      using System.Text;
      
      public partial class ServerControlWebRequest : System.Web.UI.Page
      {
          string strUri;
          protected void Page_Load(object sender, EventArgs e)
          {
              strUri = "http://localhost:1038/CustomWebAPI/Controllers/PersonController.ashx";
              btnAdd.Click += new EventHandler(btnAdd_Click);
              if (!Page.IsPostBack) getList();
          }
      
          void btnAdd_Click(object sender, EventArgs e)
          {
             
              Uri UriPath = new Uri(strUri + "?action=postPerson");
      
              StringBuilder postData = new StringBuilder();
              postData.Append(String.Format("&Id={0}&", Id.Text));
              postData.Append(String.Format("FirstName={0}&", FirstName.Text));
              postData.Append(String.Format("LastName={0}&", LastName.Text));
              postData.Append(String.Format("Department={0}", Department.Text));
      
              // set up request object
              HttpWebRequest request;
              try
              {
                  request = (HttpWebRequest)WebRequest.Create(UriPath);
              }
              catch (UriFormatException)
              {
                  request = null;
              }
              if (request == null)
                  throw new ApplicationException("Invalid URL: " + UriPath.ToString());
      
              request.KeepAlive = false;
              request.ProtocolVersion = HttpVersion.Version10;
              
              byte[] byteArray = Encoding.UTF8.GetBytes(postData.ToString());
              request.Method = "POST";
              request.ContentType = "application/x-www-form-urlencoded";
              request.ContentLength = byteArray.Length;
              request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
             
              Stream dataStream = request.GetRequestStream();
              // Write the data to the request stream.
              dataStream.Write(byteArray, 0, byteArray.Length);
              // Close the Stream object.
              dataStream.Close();
              // Get the response.
              try
              {
                  WebResponse response = request.GetResponse();
      			dataStream = response.GetResponseStream();                
      			StreamReader reader = new StreamReader(dataStream);                
      			string responseFromServer = reader.ReadToEnd();
      			
      			if (responseFromServer == "OK") getList();
                  
              }
              catch (WebException wex)
              {
                  lbltest.Text = new StreamReader(wex.Response.GetResponseStream()).ReadToEnd();
              }
            
          }
      
          private void getList()
          {
              Uri UriPath = new Uri(strUri + "?action=getPerson");
              WebRequest request = WebRequest.Create(UriPath);
              request.Method = "GET";       
             
              WebResponse response = request.GetResponse();
              Stream dataStream = response.GetResponseStream();
              StreamReader reader = new StreamReader(dataStream);
              string responseServer = reader.ReadToEnd();
                      
              JavaScriptSerializer serializer = new JavaScriptSerializer();
              List<Person> prns = serializer.Deserialize<List<Person>>(responseServer);
              foreach (Person p in prns)
              {
                  TableRow tr = new TableRow();
                  tr.Cells.Add(new TableCell() { Text = p.Id.ToString() });
                  tr.Cells.Add(new TableCell() { Text = p.FirstName });
                  tr.Cells.Add(new TableCell() { Text = p.LastName });
                  tr.Cells.Add(new TableCell() { Text = p.Department });
                  tblPersons.Rows.Add(tr);
              }
          }
      }
      

    The result is same as Client side Script. This shows us that custom Web API can be used by any method or device as long as they support HTTP.

Regards, Agung Gugiaji

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s