Last active
August 29, 2015 14:08
-
-
Save scottoffen/80b29465c66e778dd185 to your computer and use it in GitHub Desktop.
A RESTResource extension for handling JSON
This file contains 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
public abstract class MyRESTResource : RESTResource | |
{ | |
protected JObject GetJsonPayload(HttpListenerRequest request) | |
{ | |
try | |
{ | |
string data = this.GetPayload(request); | |
if (!object.ReferenceEquals(data, null)) | |
{ | |
JObject json = JObject.Parse(data); | |
return json; | |
} | |
} | |
catch (Exception e) | |
{ | |
EventLogger.Log(e); | |
} | |
return null; | |
} | |
protected void SendJsonResponse(HttpListenerContext context, object obj) | |
{ | |
var json = JsonConvert.SerializeObject(obj, Formatting.Indented); | |
var buffer = context.Request.ContentEncoding.GetBytes(json); | |
var length = buffer.Length; | |
context.Response.ContentType = ContentType.JSON.ToValue(); | |
context.Response.ContentEncoding = Encoding.UTF8; | |
context.Response.ContentLength64 = length; | |
context.Response.OutputStream.Write(buffer, 0, length); | |
context.Response.OutputStream.Close(); | |
context.Response.Close(); | |
} | |
protected void SendJsonResponse(HttpListenerContext context, JObject json) | |
{ | |
var buffer = context.Request.ContentEncoding.GetBytes(json.ToString(Formatting.Indented)); | |
var length = buffer.Length; | |
context.Response.ContentType = ContentType.JSON.ToValue(); | |
context.Response.ContentEncoding = Encoding.UTF8; | |
context.Response.ContentLength64 = length; | |
context.Response.OutputStream.Write(buffer, 0, length); | |
context.Response.OutputStream.Close(); | |
context.Response.Close(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment