web servieces 学习小栗子

苦恼啊

公司总是派我出差一出就是一个月

总这么着日子过不下去啊

媳妇都怒了

催我赶紧找工作

这就得强化能力应付笔试面试

不扯了

web services 总听这个名词儿,但是还真是没深究,因为项目中也没用到,查了点资料,也自己做了个小栗子,顺便也留个存。

1.首先,打开vs创建一个web项目,就默认名了。

2.然后添加一个web服务,后缀就是.asmx,还是默认名。

3.WebServiece1.asmx文件默认代码,可以看到有一个默认的helloworld方法,那我就不写了,真心是懒。

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.Services;
 6 
 7 namespace WebApplication3
 8 {
 9     /// <summary>
10     /// WebService1 的摘要说明
11     /// </summary>
12     [WebService(Namespace = "http://tempuri.org/")]
13     [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
14     [System.ComponentModel.ToolboxItem(false)]
15     // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。 
16     [System.Web.Script.Services.ScriptService]
17     public class WebService1 : System.Web.Services.WebService
18     {
19 
20         [WebMethod]
21         public string HelloWorld()
22         {
23             return "Hello World";
24         }
25     }
26 }

4.编译运行,F5一下搞定,弹出网页。url地址要记牢,后面用的到。

5.右键点击一下解决方案里的添加服务引用。出现下面的页面,然后把上一步的地址写进去,点击转到,服务就找到了,你看,helloworld都在。确定就行了。

6.新建个.aspx当显示页面。代码如下:就是用jquery ajax么,请求地址就是咱们刚搞的服务再加上方法名,路由策略么,大家都懂。

 1 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication3.WebForm1" %>
 2 
 3 <!DOCTYPE html>
 4 
 5 <html xmlns="http://www.w3.org/1999/xhtml">
 6 <head runat="server">
 7 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
 8 <script type="text/javascript" src="Scripts/jquery-1.7.1.min.js"></script>
 9     <title></title>
10 </head>
11 <body>
12     <form id="form1" runat="server">
13     <div>
14     <button type="button" onclick="click()">点击</button>
15     </div>
16     </form>
17 </body>
18 <script type="text/javascript">
19     function click() {
20         $.ajax({
21             type: 'POST',
22             url: 'WebService1.asmx/HelloWorld',
23             dataType: 'json',
24             contentType: "application/json",
25             success: function (data) {
26                 alert(data.d);
27             }
28         });
29     };
30 </script>
31 </html>

5.按个F5,页面出现了,测试一下。成功!

总结:做完了感觉,web services 感觉高大上,实际上就是一个公用接口,谁想用就用。这是很简单的例子,继续学习可能会有不同的砍伐。

ps:如果想的不对,请路过的大牛当头棒喝。跪谢

原文地址:https://www.cnblogs.com/sanqianjun/p/3780322.html