Skip to content

Instantly share code, notes, and snippets.

@scottoffen
Created May 1, 2014 17:53
Show Gist options
  • Save scottoffen/6a58e32635a97c9088e0 to your computer and use it in GitHub Desktop.
Save scottoffen/6a58e32635a97c9088e0 to your computer and use it in GitHub Desktop.
Grapevine.RestServer Extensions for JSON Request/Responses
using System;
using System.IO;
using System.Net;
using System.Text;
using Grapevine;
using Newtonsoft.Json.Linq;
namespace YourNameSpace
{
class ExtendedRestServer
{
protected JObject GetJsonPayload(HttpListenerRequest request)
{
JObject json = null;
string jsonstring = null;
try
{
using (var reader = new StreamReader(request.InputStream, request.ContentEncoding))
{
jsonstring = reader.ReadToEnd();
}
json = JObject.Parse(jsonstring);
}
catch { }
return json;
}
protected void SendJsonResponse(HttpListenerContext context, JObject json)
{
var buffer = context.Request.ContentEncoding.GetBytes(json.ToString());
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