HttpWebResponse from WebException

using (var response = (HttpWebResponse)((Func<WebResponse>)(() =>
{
  try { return(request.GetResponse());}
  catch (WebException ex) { return(ex.Response); }
}))()) //<-- too funny
using (var responseStream = response.GetResponseStream())
// ReSharper disable once AssignNullToNotNullAttribute
using (var readStream = new StreamReader(responseStream, Encoding.UTF8))
{
  return String.Format("{0} {1}. {2}", (int)response.StatusCode, response.StatusCode, readStream.ReadToEnd());
}

Leave a Reply