从ASMX web服务调用方法-error-



我正试图编写一个应用程序(简单的形式),将消费(调用)web服务(Service1.asmx)并显示结果。现在,web服务有了一个方法。下面是代码:

public class Service1 : System.Web.Services.WebService
{
    [WebMethod]
    public Customer getCustomer(String id)
    {
        Customer customer = new Customer();
        customer.CustomerId = id;
        customer.CustomerName = "ABC Warehouse";
        customer.CustomerAddress = "123 Anywhere";
        customer.CustomerCity = "Pittsburgh";
        customer.CustomerState = "PA";
        customer.CustomerZip = 10379;
        customer.CustomerContact = "Dan Smith";
        customer.CustomerPhone = "2484567890";
        customer.CustomerCredit = "True";
        return customer;
    }
} 

当我从其原始项目运行web服务时,我可以在文本框Example中键入文本并单击invoke以查看xml resultexample。现在,我在另一个项目中的简单表单有一个文本框(txt1)、按钮(btn1)和标签(lbl1)。我成功地添加了web服务,并将所有的函数和类进行了转换。现在,我想要的是,当您在文本框中键入一些内容时,单击submit,并在标签中查看xml结果,该结果将包括从文本框中键入的文本,就像我自己运行服务一样。下面是我遇到麻烦的代码:

    public partial class _Default : System.Web.UI.Page
    {
        protected void btn1_Click(object sender, EventArgs e)
        {
            MyService.Service1 service = new MyService.Service1();
            string message = service.getCustomer(string id);
            ID = txt1.Text;
            lbl1.Text = message; 
        }
    }

我哪里错了?我显然是一个初学者,所以所有的帮助将不胜感激。注:MyService是我添加web服务

时命名的名称空间。

你的代码将无法编译,因为getCustomer返回Customer对象。

    protected void btn1_Click(object sender, EventArgs e)
    {
        MyService.Service1 service = new MyService.Service1();
        MyService.Customer customer= service.getCustomer(string id);
        ID = customer.CustomerId;
        // here you can generate XML based on customer object if you really need to do so
        lbl1.Text = GetCustomerXML(customer);// implement method to get XML
    }
    private string GetCustomerXML( MyService.Customer  customer)
    {
        XmlSerializer xsSubmit = new XmlSerializer(typeof(MyService.Customer));
        StringWriter sw= new StringWriter();
        XmlWriter writer = XmlWriter.Create(sw);
        xsSubmit.Serialize(writer, customer);
        return sw.ToString(); 
    }

首先,在service方法中需要定义响应格式数据必须是XML格式。然后在客户端使用'XmlNode'从服务中获取数据。我想这篇文章对你会很有用

您的错误是认为您将获得XML。你不是。你会得到一个MyService.Customer

仅供参考,您应该使用"添加服务引用"来使用.asmx服务。