Skip to content

Instantly share code, notes, and snippets.

@scottoffen
Last active August 29, 2015 14:08
Show Gist options
  • Save scottoffen/80b29465c66e778dd185 to your computer and use it in GitHub Desktop.
Save scottoffen/80b29465c66e778dd185 to your computer and use it in GitHub Desktop.
A RESTResource extension for handling JSON
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