【问题标题】:Issues passing an Xml file to a method in console application将 Xml 文件传递​​给控制台应用程序中的方法的问题
【发布时间】:2015-06-25 14:46:58
【问题描述】:

我正在开发 ac# 控制台应用程序,我正在使用 xml 文件将 Http Post request 制作为 Web api,我对 XML 和 Web 服务有点陌生,但我想出了以下代码请求但未能将xml data 传递给方法

static void Main(string[] args)
        {
            string desturl=@"https://xyz.abcgroup.com/abcapi/";
            Program p = new Program();
            System.Console.WriteLine(p.WebRequestPostData(desturl, @"C:\Applications\TestService\FixmlSub.xml"));
        }

        public  string WebRequestPostData(string url, string postData)
        {
            System.Net.WebRequest req = System.Net.WebRequest.Create(url);

            req.ContentType = "text/xml";
            req.Method = "POST";

            byte[] bytes = System.Text.Encoding.ASCII.GetBytes(postData);
            req.ContentLength = bytes.Length;

            using (Stream os = req.GetRequestStream())
            {
                os.Write(bytes, 0, bytes.Length);
            }

            using (System.Net.WebResponse resp = req.GetResponse())
            {
                if (resp == null) return null;

                using (System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream()))
                {
                    return sr.ReadToEnd().Trim();
                }
            }
        }

由于显而易见的原因,上面的代码抛出 404 错误,因为我认为我没有正确传递 xml data

我可以知道如何解决这个问题吗?

【问题讨论】:

  • 404 表示找不到 URL。您需要激活一些身份验证机制才能从 System.Net.WebRequest 中检索 https:// 内容,例如参见 stackoverflow.com/questions/560804/…
  • 那么,我是否正确传递了 xml 数据?

标签: c# xml web-services http-post


【解决方案1】:

您不是在发布 xml,而是在发布字符串 C:\Applications\TestService\FixmlSub.xml

从以下位置更改您的方法调用:

System.Console.WriteLine(p.WebRequestPostData(desturl, @"C:\Applications\TestService\FixmlSub.xml"));

var xml = XElement.Load(@"C:\Applications\TestService\FixmlSub.xml");
System.Console.WriteLine(p.WebRequestPostData(desturl, xml.ToString(SaveOptions.DisableFormatting));

如果您正在尝试学习 post/receive,那就去做吧。但是,如果您想使用它们,有些开源库已经过良好的测试。

Servicestack 的非免费版本。 还有他们的老free-version。我认为旧的免费版本很棒。我从未尝试过较新的。你处理对象,比如一个员工,然后将它传递给库,它会翻译成 xml 或任何 web 服务想要的。

如果需要,您可以发布整个字符串。他们也有很好的扩展方法来帮助你。

【讨论】:

  • 谢谢,你能给我推荐几个
  • @Dev 编辑显示Servicestack.我真的很喜欢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-08
  • 2011-09-03
  • 1970-01-01
  • 1970-01-01
  • 2023-04-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多