Created
May 1, 2014 17:53
-
-
Save scottoffen/6a58e32635a97c9088e0 to your computer and use it in GitHub Desktop.
Grapevine.RestServer Extensions for JSON Request/Responses
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
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