My first question is about ReadAsAsync<>. The below method works.
protected static async Task<T> JsonRequestAsync<T>(string BaseAddress, string Request)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(BaseAddress);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
try
{
HttpResponseMessage response = await client.GetAsync(Request);
response.EnsureSuccessStatusCode();
var jsonstring = await response.Content.ReadAsStringAsync();
return await Task.Run(() => Newtonsoft.Json.JsonConvert.DeserializeObject<T>(jsonstring));
}
catch (HttpRequestException ex)
{
string s = ex.StandardMessage();
throw ex;
}
}
}
But if I try using ReadAsAsync<> in System.Net.Http.Formatters the deserialization it succeeds but returns null values in the object T (see below). I got it working using ReadAsStringAsync() but it's very messy and I don't want to have to include the Newtonsoft library. Any help would be appreciated.
return await response.Content.ReasAsAsync<T>();
My second question is regarding the use of the PostAsync() method. Below are the methods that work for my json POST.
protected T JsonPost<T>(string baseuri, string post)
{
var request = WebRequest.Create(baseuri) as HttpWebRequest;
request.Method = "POST";
var byteArray = Encoding.UTF8.GetBytes(post);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
var dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
try
{
return GetDeserializedResponse<T>(request);
}
catch (Exception ex)
{
throw ex;
}
}
protected static T GetDeserializedResponse<T>(WebRequest request)
{
var response = request.GetResponse() as HttpWebResponse;
var receiveStream = response.GetResponseStream();
var readStream = new StreamReader(receiveStream, Encoding.UTF8);
var ser = new JavaScriptSerializer();
var json = readStream.ReadToEnd();
var deserializaed = ser.Deserialize<T>(json);
response.Close();
readStream.Close();
return deserializaed;
}
I've tried to convert the above to using PostAsync<> but I've failed miserably. Any suggestions or some page you can point me to would be helpful?