Created
January 6, 2017 00:21
-
-
Save goyuix/b58d81fe21a113f785a99ad7e4ff627f to your computer and use it in GitHub Desktop.
Sample ASP.NET IHttpHandler implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<%@ WebHandler Language="C#" Class="SampleHandler" %> | |
using System; | |
using System.Web; | |
using System.Web.Script.Serialization; | |
using System.Linq; | |
using System.Reflection; | |
using System.Collections.Generic; | |
namespace WECC | |
{ | |
public class SampleHandler : IHttpHandler | |
{ | |
protected HttpContext Context = null; | |
protected static readonly object[] EmptyObjectArray = new object[] { }; | |
protected static JavaScriptSerializer serializer = null; | |
protected static Dictionary<string, MethodInfo> methodTable = null; | |
public bool IsReusable { get { return false; } } | |
// any public method that returns a JSON string becomes a valid action | |
public void ProcessRequest(HttpContext context) | |
{ | |
Context = context; | |
serializer = serializer != null ? serializer : new JavaScriptSerializer(); | |
if (methodTable == null) | |
{ | |
methodTable = new Dictionary<string, MethodInfo>(); | |
this.GetType() | |
.GetMethods(BindingFlags.Instance | BindingFlags.Public) | |
.Where(m => m.ReturnType == typeof(String)) | |
.ToList() | |
.ForEach(m => methodTable.Add(m.Name, m)); | |
} | |
try | |
{ | |
if (context.Request.PathInfo != null && context.Request.PathInfo.Length > 0) | |
{ | |
var action = context.Request.PathInfo.Substring(1); | |
if (methodTable.ContainsKey(action)) | |
{ | |
context.Response.Write(methodTable[action].Invoke(this, EmptyObjectArray) as string); | |
} else { | |
throw new Exception("Unknown action"); | |
} | |
} else { | |
throw new Exception("Action Required - TODO: Add RESTful response to resources"); | |
} | |
} | |
catch (Exception ex) | |
{ | |
var json = serializer.Serialize(new | |
{ | |
error = new | |
{ | |
Message = ex.InnerException == null ? ex.Message : ex.InnerException.Message, | |
Stack = ex.InnerException == null ? ex.StackTrace : ex.InnerException.StackTrace, | |
InnerException = (ex.InnerException!=null)?ex.InnerException.Message:"" | |
} | |
}); | |
context.Response.Write(json); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment