.Net中WebService的Demo示例
2024-09-01 14:35:59
一、创建一个Web服务
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(,);
}
4.运行TestServer.asmx页面,看到下图这样一个Webserver就创建成功了
二、.net调用Webwebservice
1.新建一个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.添加一个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显示下图则成功。
最新文章
- HTTP协议学习---(九)cookie
- 16 款最流行的 JavaScript 框架
- IOS开发UI基础UIImagePickerController的属性
- SSH整合简述一
- MyBatis——实现关联表查询
- (六)6.5 Neurons Networks Implements of Sparse Autoencoder
- 修改placeholder属性
- mysql strace fsync,fdatasync
- Silicon Labs电容式触摸感应按键技术原理及应用
- word建立统一的表格样式
- ZeroMQ 教程 001 : 基本概览
- 部署alinode监控线上应用
- 【转】PHP获取重定向URL的几种方法
- day 6 元组、字典、字符串
- JavaScript之Ajax(一)创建Ajax对象
- ruby那些事儿
- cocos2dx 3.x(游戏中的储存-UserDefault)
- unity美少女动作RPG游戏源码Action-RPG Starter Kit v5.0a
- 【BZOJ】1079: [SCOI2008]着色方案(dp+特殊的技巧)
- h3c 云计算管理平台