SOAP、WSDL、UDDI
SOAP(Simple Object Access Protocal),是在分散或在分布式环境中交换信息的简单协议。
WSDL 对WebService 的解释说明文档
UDDI (通用发现、说明和集成)是Web服务的黄页
趣味理解:
Web Service 好比是一个服务供应商;
SOAP 就像是两个公司之间签的合同,约束双方按照一定的规范和标准做事;
WSDL就像说明书,告诉别人你有什么,能给别人提供什么服务;
UDDI好比你的公司需要在黄页或工商注册,方便别人查询
TestWebService1.asmx文件
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; using System.Web.Services.Protocols; namespace WebService { /// <summary> /// TestWebService1 的摘要说明 /// </summary> [WebService(Namespace = "http://www.anniya.com/api")]// [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。 [System.Web.Script.Services.ScriptService] public class TestWebService1 : System.Web.Services.WebService { [WebMethod] [SoapHeader("myHeader")] public string HelloWorld(string name) { if (!myHeader.IsValid()) { return "对不起,您没有权限访问"; } return name + ",Hello World"; } public MySoapHeader myHeader = new MySoapHeader(); [WebMethod] public List<Student> GetStudent() { return new List<Student>() { new Student() {Id = 1, Name = "张三1"}, new Student() {Id = 2, Name = "张三2"}, new Student() {Id = 3, Name = "张三3"} }; } [WebMethod(Description="根据学生列表进行处理")] public List<Student> GetStudentResultByStudentList(List<Student> student) { foreach (var stu in student) { stu.Name += ",已经处理过了"; } return student; } } public class Student { public int Id { get; set; } public string Name { get; set; } } public class MySoapHeader : SoapHeader { public string UserName { get; set; } public string Password { get; set; } public bool IsValid() { if (UserName == "admin" && Password == "123") { return true; } else { return false; } } } }
调用代码:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using WebApplicationTestWebService.ServiceReference1; namespace WebApplicationTestWebService { public partial class WebForm1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { using (TestWebService1SoapClient client = new TestWebService1SoapClient()) { MySoapHeader myHeader = new MySoapHeader(); myHeader.UserName = "admin"; myHeader.Password = "123";//用户名和密码要和调用的Web Service 一致 Response.Write(client.HelloWorld(myHeader, "yxl") + "</br>"); Response.Write("<hr/>"); Student[] students = client.GetStudent(); foreach (var student in students) { Response.Write(student.Name+"</br>"); } Response.Write("<hr/>"); foreach (var student in client.GetStudentResultByStudentList(students)) { Response.Write(student.Name + "</br>"); } } } } }
如果使用ajax调用并且跨域的话,可以在本地应用程序中调用webservice,然后在用js调用本地应用程序,这样就不会跨域了
Web Service 使用
时间: 2024-11-05 23:21:24