Call Web API Using Generic Handler In ASP.NET

In this article I will explain how to call Web API using generic handler in ASP.NET and how to pass data from generic handler to Web API.

Before starting working on WEB API, first we need some information about WEB API.

What is WEB API

Basically Web API is the framework for creating HTTP Services and these services consume by the client like web browsers, mobile, iPhone and some other devices. If we want to expose our service data to the browsers, firstly we should have an API which is compatible with the client means with the browsers.

Web API is the best framework for transferring data and services to different other devices and one more thing about the Web API is that it is an open source framework and ideal platform for creating RESTful services in the .NET framework.

Let us see WEB API in the project

Step 1: Start Visual Studio.


Step 2: Now for creating a website, click on the File, go to New and click on the Project.


Step 3: Now we will select the ASP.NET MVC 4 Web Application and click on the OK button.


After selecting MVC 4, we will select Web API in the next generated window and click on the OK button.


Step 4: Now the solution explorer looks like the following screenshot:


Step 5: Now in the Controller folder add the controller and give the name of the controller whatever you want according to the requirement. By default the following code is added in the Controller.


  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6.   
  7. namespace MVC.Controllers {  
  8.     public class RegistrationController: Controller {  
  9.         //  
  10.         // GET: /Registration/  
  11.   
  12.         public ActionResult Index() {  
  13.             return View();  
  14.         }  
  15.   
  16.     }  
  17. }  

Step 6: Now call Web API using the Generic handler, and  write the following code in the generic handler

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using McnTracker.Models;  
  6. using System.Data;  
  7. using System.Data.SqlClient;  
  8. using System.Web.Script.Serialization;  
  9. using System.IO;  
  10. using System.Net;  
  11. using System.Net.Http;  
  12. using System.Net.Http.Headers;  
  13. using System.Configuration;  
  14. using System.Web.UI;  
  15.   
  16.   
  17. namespace McnTrackerWeb {  
  18.     /// <summary>  
  19.     /// Summary description for Registration1  
  20.     /// </summary>  
  21.     public class Registration1: IHttpHandler {  
  22.         /// <summary>  
  23.         /// This method for posting the data to the web api  
  24.         /// </summary>  
  25.         /// <param name="context"></param>  
  26.   
  27.         public void ProcessRequest(HttpContext context) {  
  28.             context.Response.ContentType = "text/xml";  
  29.             UserRegistration rs = new UserRegistration();  
  30.             rs.UserName = context.Request.QueryString["User"].ToString();  
  31.             rs.Email = context.Request.QueryString["Email"].ToString();  
  32.             rs.pass = context.Request.QueryString["Pass"].ToString();  
  33.             rs.Phone = Convert.ToInt64(context.Request.QueryString["Phone"]);  
  34.             rs.States = context.Request.QueryString["States"].ToString();  
  35.             rs.City = context.Request.QueryString["City"].ToString();  
  36.             HttpClient httpClient = new HttpClient();  
  37.             httpClient.DefaultRequestHeaders.Accept.Add(  
  38.             new MediaTypeWithQualityHeaderValue("application/json"));  
  39.             HttpResponseMessage response;  
  40.             response = httpClient.PostAsJsonAsync(ConfigurationManager.AppSettings["ApiUrl"] + "Registration/UserRegistration/", rs).Result;  
  41.             context.Response.Write("<script type='text/javascript'>alert('Registered Sucessfully');</script>");  
  42.   
  43.         }  
  44.         public bool IsReusable {  
  45.             get {  
  46.                 return false;  
  47.             }  
  48.         }  
  49.   
  50.   
  51.     }  
  52. }  

Step 7: After writing the code in the generic handler, now we need to write the code for responding the values in Web API controller.

We write the following code in the Registration controller.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Net.Http;  
  6. using System.Web.Http;  
  7. using McnTracker.Models;  
  8. using McnTracker.Core;  
  9.   
  10. namespace McnTrackerAPI.Controllers {  
  11.     public class RegistrationController: ApiController {#region Variable  
  12.         /// <summary>  
  13.         /// This variable is used for RegistrationBAL  
  14.         /// </summary>  
  15.         RegistrationBAL registraionBL;#endregion  
  16.  
  17.         #region Http Response Method  
  18.   
  19.         /// <summary>  
  20.         /// This method is used to register the details of user  
  21.         /// </summary>  
  22.         /// <param name="registration"></param>  
  23.         /// <returns></returns>  
  24.         [HttpPost, ActionName("UserRegistration")]  
  25.         public HttpResponseMessage UserRegistration(UserRegistration registration) {  
  26.             HttpResponseMessage response;  
  27.             registraionBL = new RegistrationBAL();  
  28.             try {  
  29.                 var result = registraionBL.SaveUserregisrationBL(registration);  
  30.                 response = Request.CreateResponse(HttpStatusCode.OK, result);  
  31.                 //if(result==1)  
  32.                 //{  
  33.                 // Response.Write("<script type='text/javascript'>alert('Sucess');</script>");  
  34.                 //}  
  35.   
  36.   
  37.             } catch (Exception) {  
  38.                 response = Request.CreateResponse(HttpStatusCode.InternalServerError);  
  39.             }  
  40.             return response;  
  41.         }#endregion  
  42.     }  
  43. }  
Step 8: Now run the Application and see what happens in the code. At the execution time two window executes, first is for the API and another one is for the Web Form.

Now check generic handler posting the values in Web API or not.

Fill the details and click on the submit button.


After debugging in the application we show that registration class object have values as in the following screenshot:


Summary

I hope this article is helpful for the users who want to use web API and generic handler for posting the value from the generic handler to Web API in ASP.NET.