// Collection of code snippets by Arne Vajhøj // (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) using System; using System.IO; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Web; using System.Web.Script.Serialization; using System.Xml.Serialization; namespace Ws.Rest.ASHX { [XmlRoot(ElementName="t1")] public class T1 { public int f1 { get; set; } public string f2 { get; set; } public T1() : this(0, "") { } public T1(int f1, string f2) { this.f1 = f1; this.f2 = f2; } } [XmlRoot(ElementName="t1array")] public class T1Array { [XmlElement(ElementName="t1")] public T1[] t1array { get; set; } public T1Array() : this(new T1[0]) { } public T1Array(T1[] array) { this.t1array = array; } } public class Test { public T1 GetOne(int f1) { // dummy implementation return new T1(f1, "getOne"); } public T1[] GetAll() { // dummy implementation T1[] res = new T1[3]; res[0] = new T1(1, "getAll #1"); res[1] = new T1(2, "getAll #2"); res[2] = new T1(3, "getAll #3"); return res; } public T1[] GetSome(int start, int finish) { // dummy implementation T1[] res = new T1[finish - start + 1]; for(int i = 0; i < res.Length; i++) { res[i] = new T1(start + i, "getSome #" + (start + i)); } return res; } public bool Save(T1 o) { // dummy implementation return o.f1 > 0 && o.f2.Length > 0; } public bool Delete(int f1) { // dummy implementation return f1 > 0; } } public static class Util { public static string Object2XML(object o) { XmlSerializer ser = new XmlSerializer(o.GetType()); using(StringWriter sw = new StringWriter()) { ser.Serialize(sw, o); return sw.ToString().Replace("utf-16", "utf-8"); // StringWriter end up with "utf-16" which is not good; } } public static T XML2Object(string xml) { XmlSerializer ser = new XmlSerializer(typeof(T)); using(StringReader sr = new StringReader(xml)) { return (T)ser.Deserialize(sr); } } public static string Object2JSON(object o) { JavaScriptSerializer ser = new JavaScriptSerializer(); StringBuilder sb = new StringBuilder(); ser.Serialize(o, sb); return sb.ToString(); } public static T JSON2Object(string xml) { JavaScriptSerializer ser = new JavaScriptSerializer(); return (T)ser.Deserialize(xml, typeof(T)); } public static string Object2String(object o, string typ) { if(typ == "application/xml") { return Util.Object2XML(o); } else if(typ == "application/json") { return Util.Object2JSON(o); } else { throw new Exception("Unknown type: " + typ); } } public static T String2Object(string s, string typ) { if(typ == "application/xml") { return Util.XML2Object(s); } else if(typ == "application/json") { return Util.JSON2Object(s); } else { throw new Exception("Unknown type: " + typ); } } public static string GetAllLines(Stream stm) { using(StreamReader sr = new StreamReader(stm)) { return sr.ReadToEnd(); } } } public class TestHandler : IHttpHandler { private static string GetPathQuery(HttpRequest request) { string reqinfo = request.RawUrl; int ix = reqinfo.IndexOf(".ashx"); reqinfo = reqinfo.Substring(ix + ".ashx".Length); return reqinfo; } private static void WriteResponse(HttpRequest request, HttpResponse response, object result) { response.StatusCode = (int)HttpStatusCode.OK; string acctyp = request.AcceptTypes[0]; response.ContentType = acctyp; if(acctyp == "application/xml") { response.Write(Util.Object2XML(result)); } else if(acctyp == "application/json") { response.Write(Util.Object2JSON(result)); } else { throw new Exception("Invalid accept type: " + acctyp); } } private static T ReadRequestBody(HttpRequest request) { string contyp = request.ContentType.Split(';')[0]; if(contyp == "application/xml") { return Util.XML2Object(Util.GetAllLines(request.InputStream)); } else if(contyp == "application/json") { return Util.JSON2Object(Util.GetAllLines(request.InputStream)); } else { throw new Exception("Invalid content type: " + contyp); } } private readonly Regex getOne = new Regex("^/t1/(\\d+)$"); private readonly Regex getAll = new Regex("^/t1$"); private readonly Regex getSome = new Regex("^/t1\\?start=(\\d+)&finish=(\\d+)$"); private Test real = new Test(); public void ProcessRequest (HttpContext ctx) { HttpRequest request = ctx.Request; HttpResponse response = ctx.Response; response.Headers.Add("Access-Control-Allow-Origin", "*"); string reqinfo = GetPathQuery(request); Match mone = getOne.Match(reqinfo); Match mall = getAll.Match(reqinfo); Match msome = getSome.Match(reqinfo); switch(request.HttpMethod) { case "GET": if(mone.Success) { int f1 = int.Parse(mone.Groups[1].Value); T1 result = real.GetOne(f1); WriteResponse(request, response, result); } else if(mall.Success) { T1[] result = real.GetAll(); if(request.AcceptTypes[0] == "application/xml") WriteResponse(request, response, new T1Array(result)); else WriteResponse(request, response, result); } else if(msome.Success) { int start = int.Parse(msome.Groups[1].Value); int finish = int.Parse(msome.Groups[2].Value); T1[] result = real.GetSome(start, finish); if(request.AcceptTypes[0] == "application/xml") WriteResponse(request, response, new T1Array(result)); else WriteResponse(request, response, result); } else { throw new Exception("Invalid URL: " + reqinfo); } break; case "POST": if(mall.Success) { T1 o = ReadRequestBody(request); if(real.Save(o)) { WriteResponse(request, response, o); } else { response.StatusCode = (int)HttpStatusCode.NotFound; response.StatusDescription = o.f1 + " not found"; } } else { throw new Exception("Invalid URL: " + reqinfo); } break; case "PUT": if(mone.Success) { int f1 = int.Parse(mone.Groups[1].Value); T1 o = ReadRequestBody(request); if(o.f1 == f1 && real.Save(o)) { response.StatusCode = (int)HttpStatusCode.NoContent; } else { response.StatusCode = (int)HttpStatusCode.NotFound; response.StatusDescription = f1 + " not found"; } } else { throw new Exception("Invalid URL: " + reqinfo); } break; case "DELETE": if(mone.Success) { int f1 = int.Parse(mone.Groups[1].Value); if(real.Delete(f1)) { response.StatusCode = (int)HttpStatusCode.NoContent; } else { response.StatusCode = (int)HttpStatusCode.NotFound; response.StatusDescription = f1 + " not found"; } } else { throw new Exception("Invalid URL: " + reqinfo); } break; case "OPTIONS": response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); response.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Accept"); response.StatusCode = (int)HttpStatusCode.NoContent; break; } } public bool IsReusable { get { return true; } } } }