实现原理,通过POST SOAP 1.2协议内容,实现复杂对象的传入
POST /Main.asmx HTTP/1.1
Host: localhost
Content-Type: application/soap+xml; charset=utf-8
Content-Length: length
<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
<soap12:Body>
<HelloWorld xmlns="http://tempuri.org/">
<user>
<UserID>int</UserID>
<UserName>string</UserName>
</user>
</HelloWorld>
</soap12:Body>
</soap12:Envelope>
WebService User.cs 传入对象
public class User
{
public int UserID { get; set; }
public string UserName { get; set; }
}
WebService Main.asmx.cs 服务
[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 Main : System.Web.Services.WebService
{ [WebMethod]
public string HelloWorld(User user)
{
return "Hello World" + user.UserName;
}
}
HTML页
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="_Script/jquery-1.6.4.js" type="text/javascript"></script>
<script type="text/javascript">
function makeSOAP(content) {
return '<?xml version="1.0" encoding="utf-8"?>'
+ '<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">' + ' <soap12:Body>'
+ content
+ ' </soap12:Body>'
+ '</soap12:Envelope>';
}
$(function () {
$.ajax(
{ url: "/Main.asmx",
type: "POST",
contentType: "application/soap+xml; charset=utf-8",
data: makeSOAP('<HelloWorld xmlns="http://tempuri.org/"><user> <UserID>2</UserID> <UserName>string</UserName> </user> </HelloWorld>'),
success: function (xml) {
$("#info").text($(xml).find("HelloWorldResult").text())
}
});
});
</script>
</head>
<body>
<div id="info"></div>
</body>
</html>