When extracting error response from System.Net.WebException using response stream. It gives BOM Characters. This happens in a few APIs and works for most APIs. The error is being fetched in Catch Section of the code. Here is my code
try
{
using (WebResponse response = request.GetResponse())
using (var responseStream = response.GetResponseStream())
using (FileStream fileStream = new FileStream(filePath, FileMode.Open))
{
responseStream.CopyTo(fileStream);
try // to parse the response as a valid XML
{
fileStream.Position = 0;
using (XmlReader reader = XmlReader.Create(fileStream))
{
reader.MoveToContent();
if (reader.LocalName == "html")
throw new Exception("Response from server is in html format.");
}
}
catch (Exception ex)
{
throw new Exception("Could not fetch response from server." + ex.Message);
}
}
return filePath;
}
catch (WebException ex)
{
String responseMessage = String.Empty;
String errorMessage = ex.InnerException != null ? ex.InnerException.Message : ex.Message;
if (ex.Response != null)
{
using (var streamReader = new StreamReader(ex.Response.GetResponseStream(), Encoding.UTF8))
{
responseMessage = streamReader.ReadToEnd();
}
}
}
What could be the reason behind this?