Skip to content

Instantly share code, notes, and snippets.

@woloski
Created January 27, 2012 18:01
Show Gist options
  • Save woloski/1690053 to your computer and use it in GitHub Desktop.
Save woloski/1690053 to your computer and use it in GitHub Desktop.
WCF Web API dynamic JsonNet
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.ApplicationServer.Http;
using System.ServiceModel;
using System.Net.Http;
using System.ServiceModel.Web;
using System.Net.Http.Headers;
using WebApiContrib.Formatters.JsonNet;
namespace TestSerializationWcf
{
class Program
{
static void Main(string[] args)
{
string endpoint = "http://localhost:232/test";
var config = new WebApiConfiguration();
config.EnableTestClient = true;
config.Formatters.Insert(0, new JsonNetFormatter());
using (var host = new HttpServiceHost(typeof(MyService), config, endpoint))
{
host.Open();
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.BaseAddress = new Uri(endpoint);
var response = client.PostAsync("", new ObjectContent<SampleMessage>(new SampleMessage { Foo = "bar", Blah = new { StringType = "AAA" } },
new MediaTypeWithQualityHeaderValue("application/json"), new[] { new JsonNetFormatter() })).Result;
var result = response.Content.ReadAsAsync<SampleOutput>(new [] { new JsonNetFormatter() }).Result;
Console.WriteLine(result.Foo);
dynamic a = result.Blah;
Console.WriteLine(a.Boo);
Console.ReadLine();
}
}
}
[ServiceContract]
class MyService
{
[WebInvoke(UriTemplate = "")]
public HttpResponseMessage<SampleOutput> Test(HttpRequestMessage<SampleMessage> request)
{
SampleMessage req = request.Content.ReadAsAsync().Result;
SampleOutput output = new SampleOutput { Foo = req.Foo, Blah = new { Boo = req.Blah.StringType } };
return new HttpResponseMessage<SampleOutput>(output);
}
}
public class SampleMessage
{
public string Foo { get; set; }
public dynamic Blah { get; set; }
}
public class SampleOutput
{
public string Foo { get; set; }
public dynamic Blah { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment