How To Create a Servlet (ashx) in .NET using Visual Studio C#

Creating a servlet is very simple, once you know the mechanics.  Just like  a Java Servlet is just a bunch of methods to handle HTTPRequests and HTTPResponses so is the Generic Handler class in Microsoft (dot) Net which implements the IHTTPHandler interface. Although less used, the .NET API has a HTTPResponse class and a HTTPRequest class  and HTTPContext to provide similar functionality as Java Servlets. Developers tend to home in on Microsoft Web Services rather than use the HTTPRequest and HTTPResponse when developing applications.

One reason for this may be that one could argue that Web Services are faster than HTTP. This may be so for heavy transaction applications but for run of the mill applications with light to medium workloads, transfer times are negligible.

This article is a quick little diddee to help you get started with the HTTPRequest and HTTPResponse classes in the .NET framework. As it turns out, there is also a Visual Studio Solution template to implement these two classes. If you go into Visual Studio, create a new Solution under the Web node in C#.

Select the Generic Handler template under the Web node. This will create a Handler1.ashx file and a Handler1.ashx.cs file for the code behind C# code. The template provides all the necessary code to get started quickly. Below is the code from the template. In addition I have added a snippet of code to demonstrate how to extract data from parameters, assuming that you are using the POST method.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Xml.Linq;

namespace SalesforceWS
{
   /// <summary>
   /// Summary description for $codebehindclassname$
   /// </summary>
   [WebService(Namespace = "http://tempuri.org/")]
   [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
   public class Handler1 : IHttpHandler
   {
       public void ProcessRequest(HttpContext context)
       {
          
           context.Response.ContentType = "text/plain";


           //Code snippet to get parameter value
            string param = context.Request.Params["paramname"];
          
          //example on one way of using the parameter value
           switch (param)
           {
               case "somevalue":
	     /*You can write back simple text just like in Java or PHP or Ruby or some other server side application that supports HTTPRequests and HTTResponses*/

                   context.Response.Write("write back some text");
                   
                   break;
               case "othervalue":
	     /*
	      * You can also write back the result from a method or another class.
	      * 
    */
                   context.Response.Write(GetSomeDataMethodLikeJava());
                   break;
           
           }
       }

       public bool IsReusable
       {
           get
           {
               return false;
         
           
           }
       }

       public string GetSomeDataMethodLikeJava()
       {
           String somevalue;

		//Add code

           return somevalue;

       }
   }
}
The HTTPContext, HTTPRequest and HTTPResponse classes in Microsoft (dot) Net supports all the same features as other technologies like Java, PHP, Pyhton or Ruby. Also the file name extensions is ashx and ashx.cs which is different than the Web Services  which is asmx and asmx.cs respectively.

If you would like more information on the subject or have specific questions regarding the HTTPRequest, HTTPResponse or HTTPContext., leave me a comment and I will get back as quickly as possible. If you have suggestions to improve on the article, again leave a comment. I would love the feedback.

More by this Author


Comments

No comments yet.

    Sign in or sign up and post using a HubPages Network account.

    0 of 8192 characters used
    Post Comment

    No HTML is allowed in comments, but URLs will be hyperlinked. Comments are not for promoting your articles or other sites.


    Click to Rate This Article
    working