Monthly Archives: July 2015

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.

Continue reading

Advertisements