Skip to content

Instantly share code, notes, and snippets.

@morbidcamel101
Last active August 29, 2015 14:16
Show Gist options
  • Select an option

  • Save morbidcamel101/ac937a0db3c1bfc56c34 to your computer and use it in GitHub Desktop.

Select an option

Save morbidcamel101/ac937a0db3c1bfc56c34 to your computer and use it in GitHub Desktop.
Async JSON Response
public interface IResponse
{
bool IsSuccess { get; set; }
string ErrorMessage { get; set; }
}
...
public static Task<T> GetResponseAsync<T>(string url, string method = "POST") where T: IResponse, new()
{
try
{
var request = WebRequest.CreateHttp(url);
request.Method = method;
request.ContentType = "application/json";
request.Expect = "application/json";
var r = request.GetResponseAsync();
var p = r.ContinueWith<T>(t =>
{
try
{
using (Stream stream = t.Result.GetResponseStream())
{
var serializer = JsonSerializer.CreateDefault();
JsonReader reader = new JsonTextReader(new StreamReader(stream));
return serializer.Deserialize<T>(reader);
}
}
catch(Exception ex)
{
return new T() { IsSuccess = false, ErrorMessage = ex.Message };
}
});
return p;
}
catch(Exception ex) {
return Task.FromResult(new T () { IsSuccess = false, ErrorMessage = ex.Message });
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment