Returning a string containing valid Json with Nancy

Dave picture Dave · Sep 29, 2011 · Viewed 28k times · Source

I receive a string that contains valid JSON from another service. I would like to just forward this string with Nancy but also set the content-type to "application/json" which will allow me to remove the need for using $.parseJSON(data) on the client side.

If I use Response.AsJson it seems to mangle the JSON in the string and adds escape characters. I could create a Stream with the string and set the response type something like:

Response test = new Response();
test.ContentType = "application/json";
test.Contents = new MemoryStream(Encoding.UTF8.GetBytes(myJsonString)); 

but would like to know if there is a simpler way?

Answer

Darius picture Darius · Nov 4, 2012

Looks like Nancy has got a nice Response.AsJson extension method:

Get["/providers"] = _ =>
            {
                var providers = this.interactiveDiagnostics
                                    .AvailableDiagnostics
                                    .Select(p => new { p.Name, p.Description, Type = p.GetType().Name, p.GetType().Namespace, Assembly = p.GetType().Assembly.GetName().Name })
                                    .ToArray();

                return Response.AsJson(providers);
            };