【问题标题】:Programmatically call webmethods in C#在 C# 中以编程方式调用 webmethods
【发布时间】:2010-06-04 11:04:41
【问题描述】:

我正在尝试编写一个函数,该函数可以在给定方法名称和 Web 服务 URL 的情况下从 Web 服务调用 Web 方法。我在博客上找到了一些代码,除了一个细节外,它做得很好。它还要求提供请求 XML。这里的目标是从 web 服务本身获取请求 XML 模板。我确信这是可能的,因为如果我在浏览器中访问 Web 服务的 URL,我可以同时看到请求和响应 XML 模板。

这是以编程方式调用网络方法的代码:

XmlDocument doc = new XmlDocument();
//this is the problem. I need to get this automatically
doc.Load("../../request.xml"); 
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost/dummyws/dummyws.asmx?op=HelloWorld");
req.ContentType = "text/xml;charset=\"utf-8\"";
req.Accept = "text/xml";
req.Method = "POST";
Stream stm = req.GetRequestStream();
doc.Save(stm);
stm.Close();
WebResponse resp = req.GetResponse();
stm = resp.GetResponseStream();
StreamReader r = new StreamReader(stm);
Console.WriteLine(r.ReadToEnd());

【问题讨论】:

  • 如果你不知道它需要什么参数,你怎么能调用一个方法(网络服务或其他)?
  • 我们现在假设这些网络方法不需要任何参数。
  • Web 服务是否公开 WSDL 描述?
  • 是的,网络服务公开了一个 WSDL 描述。
  • 那么您不能使用 WSDL 文件作为您的请求 XML 的定义吗?或者,更简单的是,从 WSDL 为 Web 服务生成代理?

标签: c# web-services asmx webmethod


【解决方案1】:

从上面的 cmets 开始。如果您有一个描述您的服务的 WSDL 文件,您可以将其用作与您的 Web 服务通信所需的信息。

使用代理类与您的服务代理进行通信是一种将自己从 HTTP 和 XML 的底层管道中抽象出来的简单方法。

有一些方法可以在运行时执行此操作 - 本质上是在您向项目添加 Web 服务引用时生成 Visual Studio 生成的代码。

我使用的解决方案基于:this newsgroup question,但也有 other examples out there

【讨论】:

    【解决方案2】:

    仅供参考,您的代码缺少 using 块。它应该更像这样:

    XmlDocument doc = new XmlDocument();
    //this is the problem. I need to get this automatically
    doc.Load("../../request.xml"); 
    HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost/dummyws/dummyws.asmx?op=HelloWorld");
    req.ContentType = "text/xml;charset=\"utf-8\"";
    req.Accept = "text/xml";
    req.Method = "POST";
    
    using (Stream reqstm = req.GetRequestStream())
    {
        doc.Save(reqstm);
    }
    
    using (WebResponse resp = req.GetResponse())
    {
        using (Stream respstm = resp.GetResponseStream())
        {
            using (StreamReader r = new StreamReader(respstm))
            {
                Console.WriteLine(r.ReadToEnd());
            }    
        }
    }
    

    【讨论】:

    • 你是对的,但我使用了 dariom 的解决方案,它没有使用那段代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-08
    • 1970-01-01
    • 1970-01-01
    • 2020-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多