c# - 从 C# 调用 OData 服务

标签 c# wcf rest odata

我使用下面的代码从 C# 调用 OData 服务(这是来自 Odata.org 的工作服务),但我没有得到任何结果。
错误在response.GetResponseStream()

这里是错误:

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

我想调用该服务并从中解析数据,最简单的方法是什么?

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);

                    }
                }

            }
        }
    }

最佳答案

我在我的机器上运行了你的代码,它执行得很好,我能够遍历 XmlTextReader 检索到的所有 XML 元素。

    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);
            }
        }
    }

但正如@qujck 所建议的,看一下 HttpClient。它更易于使用。

关于c# - 从 C# 调用 OData 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19264715/

相关文章:

c# - 获取设置属性从日期时间中删除时间

c# - 如何从 C# 中的 IDataReader Func 调用的另一个类中访问一个类属性

c# - NuGet Pack -Build 似乎不理解 c# 6.0

c# - 使用 NetNamedPipe 的 WCF 多个应用程序

rest - 有关使用 REST 和 Backbone 的身份验证工作流程的问题

asp.net-mvc - 是否可以在 ASP.NET MVC 中实现 X-HTTP-Method-Override?

c# - SetActive 在 Unity3d 中不起作用?

asp.net - 如何解决Kerberos双跳问题?

c# - IIS 中的 WCF,http 基本身份验证 - Windows 用户 "security"含义

java - 将图像与实体一起保存在数据库中