[英]calling methods from an ASMX web service -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結果Example 。 現在,我在另一個項目中擁有的簡單表單具有一個文本框(txt1),按鈕(btn1)和標簽(lbl1)。 我成功添加了Web服務,並且所有函數和類都已轉移。 現在,我想要發生的是,當您在文本框中鍵入內容,單擊提交,然后在標簽中查看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;
}
}
我要去哪里錯了? 我顯然是一個初學者,因此將不勝感激。 ps: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();
}
首先,在服務方法中,您需要定義響應格式數據必須為XML格式。 然后在客戶端使用'XmlNode'
從服務獲取數據。 我認為這篇文章對您有用
您的錯誤是認為您將要收回XML。 你不是。 您將獲得MyService.Customer
。
僅供參考,您應該使用“添加服務參考”來使用.asmx服務。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.