.net中WebService的使用實例


一、創建一個Webwebservice

      1.新建一個項目WebserverDemo

      2.在項目處添加新建項,添加一個web服務

   

  3.編輯TestServer.asmx文件

    3.1 TestServer.asmx默認的代碼是這樣

/// <summary>
    /// TestServer 的摘要說明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允許使用 ASP.NET AJAX 從腳本中調用此 Web 服務,請取消注釋以下行。 
    // [System.Web.Script.Services.ScriptService]
    public class TestServer : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }
        
    }

3.2 現在加多一個方法  

       [WebMethod]
        public string GetAge(string id)
        {
            return "ID為:" + id + "的年齡為:"+new Random().Next(10,41);
        }

4.運行TestServer.asmx頁面,看到下圖這樣一個Webserver就創建成功了

二、.net調用Webwebservice

   通常是把WebServer發布到iis,然后在另一個程序中調(這里為了方便直接在本程序中調用演示)

  1.項目中的引用選擇添加服務引用,地址輸入剛才那個頁面的地址。

 

 然后看項目Service References文件夾

2.新建一個WebServerData.aspx頁面,在.cs中寫

 protected void Page_Load(object sender, EventArgs e)
        {
            ServiceReference1.TestServerSoapClient testServer = new ServiceReference1.TestServerSoapClient();
            string str1= testServer.HelloWorld();
            string str2 = testServer.GetAge("b101");
            Response.Write(str1 + "," + str2);
        }

 有結果輸出剛調用成功了。

三、前端JS調用Webwebservice

 1.把TestServer.asmx 文件的允許ajax調用web服務下面一行代碼取消注釋

 2.添加一個WebServerData.html頁面

  

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <script src=" http://libs.baidu.com/jquery/1.11.1/jquery.min.js "></script>
        <script type="text/javascript">
            $(function () {
                $("#getdata").click(function () {
                    $.ajax({
                        type: 'POST',
                        url: 'TestServer.asmx/GetAge',
                        data: '{ id:"bb101"}',
                        dataType: 'json',
                        contentType: "application/json",
                        success: function (data) {
                            $("#data").append(data.d);
                        }
                    });
                });
            });
        </script>
</head>
<body>
    <a id="getdata" href="javascript:void(0);">獲取webservice數據</a>
    <div id="data"></div>
</body>
</html>

 點擊a顯示下圖則成功。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM