Just started using Web API during preview 6 then my world got flipped upside when things shifted to the ASP.NET Web API!
I wanted to get some opinions on some code I wrote usign Web API and if there were any ways I could improve it. Basically, I don't think that I need any of the async stuff right now, and don't want to upgrade and wait for .NET 4.5 to be released.
I just want the code to run like it did during preview 6.
So how does this code look to you guys/gals? All it does is attempt to read a concrete type from the response stream. For some reason, this code didn't work with the built in ReadAsAsync<T> code handling the serialization, so I instead used the Newtonsoft
JSON library:
public T GetDataFromService<T>()
{
using (var httpClient = new HttpClient())
{
T result = default(T);
Task<HttpResponseMessage> responseTask = null;
httpClient.GetAsync(_endpoint).ContinueWith((requestTask) =>
{
responseTask = requestTask;
HttpResponseMessage response = requestTask.Result;
response.EnsureSuccessStatusCode();
response.Content.ReadAsStringAsync().ContinueWith((readTask) =>
{
result = JsonConvert.DeserializeObject<T>(readTask.Result);
});
});
// HACK: My version of the await keyword
while (responseTask == null || !responseTask.IsCompleted || result == null) { }
return result;
}
}
skippyfire
Member
34 Points
31 Posts
Making a request synchronously
Feb 22, 2012 12:30 PM|LINK
Hi everyone,
Just started using Web API during preview 6 then my world got flipped upside when things shifted to the ASP.NET Web API!
I wanted to get some opinions on some code I wrote usign Web API and if there were any ways I could improve it. Basically, I don't think that I need any of the async stuff right now, and don't want to upgrade and wait for .NET 4.5 to be released. I just want the code to run like it did during preview 6.
So how does this code look to you guys/gals? All it does is attempt to read a concrete type from the response stream. For some reason, this code didn't work with the built in ReadAsAsync<T> code handling the serialization, so I instead used the Newtonsoft JSON library:
public T GetDataFromService<T>() { using (var httpClient = new HttpClient()) { T result = default(T); Task<HttpResponseMessage> responseTask = null; httpClient.GetAsync(_endpoint).ContinueWith((requestTask) => { responseTask = requestTask; HttpResponseMessage response = requestTask.Result; response.EnsureSuccessStatusCode(); response.Content.ReadAsStringAsync().ContinueWith((readTask) => { result = JsonConvert.DeserializeObject<T>(readTask.Result); }); }); // HACK: My version of the await keyword while (responseTask == null || !responseTask.IsCompleted || result == null) { } return result; } }