﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Collections.Specialized;
using System.Web.Script.Serialization;
using Common;
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
using System.IO;
using System.Xml;
namespace ConsoleApplication1
{
class Program
{
internal static DataContractJsonSerializer jss;
private static WebClient client = new WebClient();
private static NameValueCollection values = new System.Collections.Specialized.NameValueCollection();
static void Main(string[] args)
{
//Use ModelBinding in WebSite to resolve types to Controller Actions
Person pers = new Person(1, "name", null);
AddValue(values,"person", pers);
//NOTE : WebClient doesn't allow you to set ContentType header to "application/json"
// which is a shame as it would be very nice. But since the WebClient allows
// you to add anything to its collection of values, it makes sense to restrict the
// WebClient ContentType header to "application/x-www-form-urlencoded" (the default)
// as you can't really know what data you are sending, could be anything being sent up
// in one go, so what ContentType could be reasonably provided except
// "application/x-www-form-urlencoded"
// Also the WebClient is kind of a dumbed down HttpRequest, so its more limited, but also
// more convenient
Byte[] results = client.UploadValues("http://localhost:8300/Rest/Index", values);
//get results
List<Person> people = GetValue<List<Person>>(results);
Console.ReadLine();
}
internal static T GetValue<T>(Byte[] results) where T : class
{
using (MemoryStream ms = new MemoryStream(results))
{
jss = new DataContractJsonSerializer(typeof(T));
return (T)jss.ReadObject(ms);
}
}
internal static void AddValue(NameValueCollection values, string key, object value)
{
jss = new DataContractJsonSerializer(value.GetType());
using (MemoryStream ms = new MemoryStream())
{
jss.WriteObject(ms, value);
string json = Encoding.UTF8.GetString(ms.ToArray());
values.Add(key, json);
}
}
}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.