Click here to Skip to main content
15,884,842 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
My first question is about ReadAsAsync<>. The below method works.
C#
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.
C#
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.
C#
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?
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900