Search code examples
asp.netasp.net-mvchttp-status-code-404xmlreader

XmlReader unable to connect to remote XML using ASP.NET MVC


I'm trying to return the latitude and longitude of a UK postcode using the service http://uk-postcodes.com (e.g. http://uk-postcodes.com/postcode/G38EU.xml).

This is working great when I try visiting the URL in my browser, but whenever I try it within my ASP.NET MVC project I'm getting a 404 exception returned?

I was wondering if this is because I'm only running the code on my localhost, instead of on a remote server? If so I can just insert test values for this, but thought I'd check to see if anyone has any experience of this!

Thanks for any help, Steven.

Please see the code below:

// Get the XML document
XmlReader xmlReader = XmlReader.Create("http://uk-postcodes.com/postcode/" + postcode + ".xml");

// Loop through the XML document
while (xmlReader.Read())
{
    // Get the latitude coordinate
    if ((xmlReader.NodeType == XmlNodeType.Element) && (xmlReader.Name == "lat"))
    {
        coordinates.Add(xmlReader.Value);
    }

    // Get the longitude coordinate
    if ((xmlReader.NodeType == XmlNodeType.Element) && (xmlReader.Name == "lng"))
    {
        coordinates.Add(xmlReader.Value);
    }

    break;
}

Solution

  • Its working as expected after removing the break within the while loop.

                var coordinates = new List<string>();
                string postcode = "KA278AA";
    
                // Get the XML document
                XmlReader xmlReader = XmlReader.Create("http://uk-postcodes.com/postcode/" + postcode + ".xml");
    
                // Loop through the XML document
                while (xmlReader.Read())
                {
                    // Get the latitude coordinate
                    if ((xmlReader.NodeType == XmlNodeType.Element) && (xmlReader.Name == "lat"))
                    {
                        coordinates.Add(xmlReader.ReadInnerXml());
                    }
    
                    // Get the longitude coordinate
                    if ((xmlReader.NodeType == XmlNodeType.Element) && (xmlReader.Name == "lng"))
                    {
                        coordinates.Add(xmlReader.ReadInnerXml());
                    }
                }