星空网 > 软件开发 > ASP.net

.net中WebService的使用实例

一、创建一个Webwebservice

      1.新建一个项目WebserverDemo

      2.在项目处添加新建项,添加一个web服务

   .net中WebService的使用实例

  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中WebService的使用实例

二、.net调用Webwebservice

   通常是把WebServer发布到iis,然后在另一个程序中调(这里为了方便直接在本程序中调用演示)

  1.项目中的引用选择添加服务引用,地址输入刚才那个页面的地址。

.net中WebService的使用实例

 

 然后看项目Service References文件夹

.net中WebService的使用实例

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 "http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>  <title></title>  <script src='/images/loading.gif' data-original=" 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显示下图则成功。

.net中WebService的使用实例




原标题:.net中WebService的使用实例

关键词:.NET

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

节税账户:https://www.goluckyvip.com/tag/34696.html
杰驰国际:https://www.goluckyvip.com/tag/34697.html
杰美特:https://www.goluckyvip.com/tag/34698.html
杰说电商:https://www.goluckyvip.com/tag/34699.html
12月营销节日:https://www.goluckyvip.com/tag/347.html
爆款产品:https://www.goluckyvip.com/tag/3470.html
去日本入住酒店,东西随意用却有一个特殊“要:https://www.vstour.cn/a/411241.html
中国有哪些著名的酒店品牌。:https://www.vstour.cn/a/411242.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流