【原創】ASP.NET Web Service 建立、部署與使用

來源:互聯網
上載者:User

 

 

 

PS: 開發工具 VS2010, 所有工程都為Debug狀態,本人剛接觸 Web Service,此文為菜鳥入門用例,高手勿笑!

轉載請註明出處                                                                                                                  

一、建立Web Service 工程

1. 建立一個 Web Service 工程,工程名為WebServiceProject

File -> New -> Project  -->   Visual C# -> Web -> ASP.NET Web Service Application

注意: .NET Framework版本選3.5, 4.0 中沒有該類型的工程

 

2. 在WebServiceProject中,刪除 Servie1 類中原有的HelloWorld方法,添加一個方法 ReverseString 

代碼

        [WebMethod]
public string ReverseString(string s)
{
System.Threading.Thread.Sleep(5000);
char[] a = s.ToCharArray();
Array.Reverse(a);
return new string(a);
}

必須加上在方法前加上 [WebMethod] 屬性

方法中首行的 Sleep(5000) 為了展示下文中同步調用與非同步呼叫 Web Service中方法的區別

 

將   [WebService(Namespace = "http://tempuri.org/")]

改為 [WebService(Namespace = "http://WebServiceSample/")]     名字隨便取

可以不改,若不改,下一步通過瀏覽器查看時會有提示(可以自己看一下)

 

3. 編譯並測試WebServiceProject

按 F7編譯工程,通過瀏覽器查看Servic1.asmx

 

由於工程中只有一個方法,頁面顯示如下:

點擊ReverseString,可以進入該方法的測試頁面,進行測試

 

 

二、部署Web Service

1.  發布工程到本地的某一個目錄(D:\WebServiceSample)

 

  
 2. 發布完後,在IIS中添加一個指向該目錄的虛擬目錄(或應用程式)

 3. 通過 瀏覽器 查看,測試發布是否成功

http://localhost/webservicesample/service1.asmx

頁面顯示應與上一節中相同

 

三、使用Web Service

1.  使用WSDL 工具產生 Web Service 中 Servie1類的代理類

     開啟 VS2010 命名行工具

 

輸入如下命名,在D:\產生一個myProxyClass.cs檔案,裡面有一個代理類

public partial class Service1 : System.Web.Services.Protocols.SoapHttpClientProtocol

關於如何組建代理程式類的詳見

http://msdn.microsoft.com/zh-cn/library/7h3ystb6.aspx 

 

 

2. 建立一個Windows Form Application,來使用Web Service,工程名為 WebServiceClient

   在工程中添加步驟1中產生的myProxyClass.cs檔案

   添加 System.Web.Services引用:Project -> Add Reference

 

3. 在Form1上,拖入幾個控制項

 

4.  為按鈕添加事件響應函數

        //同步
private void button1_Click(object sender, EventArgs e)
{
Service1 ws = new Service1();
textBox2.Text = ws.ReverseString(textBox1.Text);
}

//非同步
private void button2_Click(object sender, EventArgs e)
{
Service1 ws = new Service1();
ws.ReverseStringCompleted += new ReverseStringCompletedEventHandler(ReverseStringCompleted);
ws.ReverseStringAsync(textBox1.Text);
}

private void ReverseStringCompleted(object sender, ReverseStringCompletedEventArgs e)
{
textBox2.Text = e.Result;
}

 

5.  測試程式的效果

用同步響應時,在Web Service中的方法結束前,程式無法響應

用非同步響應時,在Web Service中的方法結束前,程式可以響應

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.