.net中WebService的使用實例

1、建立一個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就建立成功了

2、.net調用Webwebservice

   一般是把WebServer發佈到iis,而後在另外一個程序中調(這裏爲了方便直接在本程序中調用演示)javascript

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

 

 而後看項目Service References文件夾html

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);
        }

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

3、前端JS調用Webwebservice

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

 2.添加一個WebServerData.html頁面java

  

<!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顯示下圖則成功。jquery

相關文章
相關標籤/搜索