C# 下 WebService 初探: 構建Web Service 服務及 WinForm和瀏覽器 http-get調用

來源:互聯網
上載者:User

在 Visual Studio 下構建 Web Service 服務非常簡單,  只需: 添加新的項目--> ASP.NET Web 服務應用程式,即可產生一個 WebService, 並有一個預設的 不帶參數的 Helloworld web方法, 也可自己添加一個帶參數的方法, 如下:

        [WebMethod]
        public string SayHello(string name)
        {
            return String.Format("Hi, {0}!", name);
        }

產生的是一個 .DLL 檔案; 也可以將 Service.asmx 發布到 IIS中去.

(一) WinForm 中調用 WebService.

1.  添加一個新的項目: Windows表單應用程式;

2.  應用 --> 添加應用, 找到上面產生的 WebService 應用程式檔案(.dll), 添加當前應用程式的應用中.

3.  添加引用 WebSerice 的命名空間, 比如 : using MyWebService;

4.  測試調用web service 的效果: 在表單上設定 2個 Button, 設定Click事件:

        private void button1_Click(object sender, EventArgs e)        {            MyWebService.Service1 localService = new Service1();            MessageBox.Show(localService.HelloWorld());        }        private void button2_Click(object sender, EventArgs e)        {            MyWebService.Service1 localService = new Service1();            string response = localService.SayHello("Tom");            MessageBox.Show(response);        }

即可.

(二) 瀏覽器下使用 Http-Get 直接調用 WebService, 即在瀏覽器下地址欄這樣調用:

http://DomainName/Service1.asmx/SayHello?name="Jick"

預設情況下, 處於安全考慮, .net 2.0 以上不支援這種協議調用. 若要這樣做, 則需要修改 web.config 設定檔, 如下增加設定項:

      <webServices>
        <protocols>
          <add name="HttpGet"/>
          <add name ="HttpPost"/>
        </protocols>
      </webServices>

這個必須放在<system.web>  ...  </system.web> 區段裡的.

當 web服務發布時 web.config 是一起發布出去的.

開啟瀏覽器, 在地址欄輸入:  http://127.0.0.1/Service1.asmx/SayHello?Name="dfasfas"

其中方法名 SayHello 大小寫是敏感的, 參數名不區分大小寫, 但名稱必須與原方法定義中是一樣的.

即可獲得如下 xml 資訊:

  <?xml version="1.0" encoding="utf-8" ?>   <string xmlns=" http://tempuri.org/"> Hi, "dfasfas"!</string>   當然這種顯示結果 UI 體驗是不友好的, 是給開發人員用於擷取 xml 資料的.  這就是對 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.