Search code examples
c#wcfrestodata

Call to OData service from C#


I use the code below to call an OData service (which is the working service from Odata.org) from C# and I don't get any result.
The error is in the response.GetResponseStream().

Here is the error :

Length = 'stream.Length' threw an exception of type 'System.NotSupportedException'

I want to call to the service and parse the data from it, what is the simpliest way to do that?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Net;
using System.IO;
using System.Xml;

namespace ConsoleApplication1
    {
    public class Class1
        {

        static void Main(string[] args)
            {
            Class1.CreateObject();
            }
        private const string URL = "http://services.odata.org/OData/OData.svc/Products?$format=atom";


        private static void CreateObject()
            {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
            request.Method = "GET";

            request.ContentType = "application/xml";
            request.Accept = "application/xml";
            using (WebResponse response = request.GetResponse())
                {
                using (Stream stream = response.GetResponseStream())
                    {

                    XmlTextReader reader = new XmlTextReader(stream);

                    }
                }

            }
        }
    }

Solution

  • I ran your code on my machine, and it executed fine, I was able to traverse all XML elements retrieved by the XmlTextReader.

        var request = (HttpWebRequest)WebRequest.Create(URL);
        request.Method = "GET";
    
        request.ContentType = "application/xml";
        request.Accept = "application/xml";
        using (var response = request.GetResponse())
        {
            using (var stream = response.GetResponseStream())
            {
                var reader = new XmlTextReader(stream);
                while (reader.Read())
                {
                    Console.WriteLine(reader.Value);
                }
            }
        }
    

    But as @qujck suggested, take a look at HttpClient. It's much easier to use.