Sunday, August 24, 2014

HTTP Web Service using ASP.NET Web API

Creating HTTP WebService using ASP.NET Web API is really simple.
 
After few reading/coding work, I got an idea on what needs to be implemented.
 
1. Make sure the routing table is configured correctly like shown below. The 'WebApiConfig' class will be present in the folder 'App_Start' folder. Note down the 'action' text added in the route.
 
public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            // Web API routes
            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
 
 
2. Create the Controller Class. See the sample class 'ManagerController' shown below. This class should be derived from 'ApiController'. Also note down the first portion of the controller class name 'Manager' and the action name 'getSomeInfo'. This will be used later when you invoke the 'HTTP Web Service'.
 
public class ManagerController : ApiController
{
        #region Public Web Methods
        [HttpGet]
        [ActionName("getSomeInfo")]
        public SomeOutputClass SomeGetWebFunction(string someInput)
        {
     // Some code goes here.
     // This should return SomeOutputClass.
  }
}
 
These are the only two steps we need.
 
Compile the application and host it in IIS Server and give some application name. For example 'TestApp'.
 
The HTTP Web Service is ready.
 
Simply call the 'WebService' as shown below and you should get the results as 'JSON' text format.

The HTTP Web Service call will be invoked like shown below.
 
 
There are many details in ASP.NET Web API. The idea I have provided will simply get you started.
 
Read more information for further details.
 
Happy Coding !
 
Cheers
Adam

 

No comments:

Post a Comment

All Blogs so far ...