sách gpt4 ăn đã đi

Phân tích tóm tắt chuyên sâu về việc gọi dịch vụ web trong .net

In lại Tác giả: qq735679552 Thời gian cập nhật: 29-09-2022 22:32:09 30 4
mua khóa gpt4 giày nike

CFSDN nhấn mạnh vào giá trị tạo ra nguồn mở và chúng tôi cam kết xây dựng nền tảng chia sẻ tài nguyên để mọi nhân viên CNTT có thể tìm thấy thế giới tuyệt vời của bạn tại đây.

Bài viết trên blog CFSDN này cung cấp một bản tóm tắt và phân tích chuyên sâu về cách gọi các webservices trong .net, được tác giả sưu tầm và biên soạn. Nếu bạn quan tâm đến bài viết này thì nhớ like nhé.

Gần đây tôi đang thực hiện một dự án. Vì tôi đang phát triển ứng dụng trong khuôn khổ của người khác nên có nhiều hạn chế là tôi không thể tham khảo trực tiếp dịch vụ web. Tất cả chúng ta đều biết rằng cách dễ nhất để gọi dịch vụ web là nhấp chuột phải vào "Tham khảo", sau đó chọn "Dịch vụ web tham chiếu", rồi nhập địa chỉ dịch vụ. Sau khi xác nhận, một app.config sẽ được tạo, nó sẽ tự động tạo một số thông tin cấu hình. Điều này không thể thực hiện được đối với dự án mà chúng tôi hiện đang thực hiện. Sau khi tìm kiếm, tôi đã tìm thấy một số cách khác để gọi động dịch vụ web. Không dài dòng nữa, đây là mã dịch vụ web.

Sao chép mã mã như sau

Xem Mã bằng System; sử dụng System.Collections.Generic; sử dụng System.Linq; sử dụng System.Web.Services; không gian tên TestWebService { /// /// Mô tả tóm tắt về Service1 /// [WebService(Namespace = "http://tempuri.org/",Description="My Web Service")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] // Để cho phép dịch vụ web này được gọi từ các tập lệnh sử dụng ASP.NET AJAX, hãy bỏ ghi chú dòng sau. // [System.Web.Script.Services.ScriptService] lớp công khai TestWebService : System.Web.Services.WebService { [WebMethod] chuỗi công khai HelloWorld() { return "Test Hello World" } [WebMethod] chuỗi công khai Test(); { return "TestTest"; } [WebMethod(CacheDuration = 60,Description = "Test")] Danh sách công khai GetPersons() { List list = Danh sách mới(); list.Add("Test One"); list.Add("Test Two" list.Add("Test Three");

Ví dụ về cách gọi động: Phương pháp 1: Tôi thấy rằng nhiều lệnh gọi động tới WebService chỉ là các địa chỉ gọi động. Đây là một địa chỉ không chỉ được gọi dựa trên địa chỉ mà tên phương thức cũng có thể do chính bạn chỉ định. phân tích WSDL dựa trên địa chỉ WebService đã chỉ định. Mô phỏng để tạo một lớp proxy và gọi các phương thức trong đó thông qua sự phản chiếu.

Sao chép mã mã như sau

Xem Mã bằng System; bằng System.IO; bằng System.Collections.Generic; bằng System.Linq; bằng System.Collections; bằng System.Web; bằng System.Net; bằng System.Reflection; bằng System.CodeDom; bằng System.CodeDom.Compiler; bằng System.Web.Services; bằng System.Text; bằng System.Web.Services.Description; bằng System.Web.Services.Protocols; bằng System.Xml.Serialization; bằng System.Windows.Forms; không gian tên ConsoleApplication1 { lớp Chương trình { tĩnh void Main(string[] args) { WebClient client = new WebClient(); Chuỗi url = "http://localhost:3182/Service1.asmx?WSDL";//这个地址可以写在Config文件里面,这里取出来就行了.在原地址后面加上: ?WSDL Luồng luồng = client.OpenRead(url); Mô tả ServiceDescription = ServiceDescription.Read(stream); ServiceDescriptionImporter nhà nhập khẩu = new ServiceDescriptionImporter();//创建客户端代理代理类。 nhà nhập khẩu.ProtocolName = "Xà phòng"; //指定访问协议。 nhà nhập khẩu.Style = ServiceDescriptionImportStyle.Client; //Không thể sử dụng dịch vụ web. importer.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync; importer.AddServiceDescription(description, null, null); //Không thể sử dụng WSDL. CodeNamespace nmspace = new CodeNamespace(); //Không thể sử dụng nmspace.Name = "TestWebService"; CodeCompileUnit unit = new CodeCompileUnit(); unit.Namespaces.Add(nmspace); ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit); CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp"); CompilerParameters parameter = new CompilerParameters(); parameter.GenerateExecutable = false; parameter.OutputAssembly = "MyTest.dll";//Trình biên dịch tệp tham chiếu tham số.ReferencedAssemblies.Add("System.dll"); parameter.ReferencedAssemblies.Add("System.XML.dll"); parameter.ReferencedAssemblies.Add("System.Web.Services.dll"); parameter.ReferencedAssemblies.Add("System.Data.dll"); CompilerResults result = provider.CompileAssemblyFromDom(parameter, unit); if (result.Errors.HasErrors) { // 显示编译错误信息 } Assembly asm = Assembly.LoadFrom("MyTest.dll");//加载前面生成的程序集 Nhập t = asm.GetType("TestWebService.TestWebService"); đối tượng o = Activator.CreateInstance(t); Phương thức MethodInfo = t.GetMethod("GetPersons");//GetPerson s是服务端的方法名称,你想调用服务端的什么方法都可以在这里改,最好封装一下String[] item = (String[])method.Invoke(o, null); //注:method.Invoke(o, null)返回的是一个Object,如果你服务端返回的是DataSet,这里也是用(DataSet)method.Invoke(o, null)转一下就行了,phương thức.Invoke(0,null)这里的null可以传调用方法需要的参数,string[]形式的 foreach (string str in item) Console.WriteLine(str); //Thông tin trên dựa trên địa chỉ WebService, mô phỏng việc tạo một lớp proxy. Nếu bạn muốn xem tệp mã được tạo trông như thế nào, bạn có thể lưu nó với mã mặc định là. để lưu nó trong thư mục bin TextWriter writer = File.CreateText("MyTest.cs"); Provider.GenerateCodeFromCompileUnit(unit, writer, writer.Flush();

Phương pháp 2: Sử dụng wsdl.exe để tạo lớp proxy dịch vụ web: Tạo lớp proxy dịch vụ web dựa trên wsdl được cung cấp, sau đó tham chiếu tệp lớp này trong mã. Các bước: 1. Tìm Công cụ Visual Studio trong Microsoft Visual Studio 2010 trong menu bắt đầu, nhấp vào Dấu nhắc lệnh của Visual Studio (2010) và mở dòng lệnh. 2. Nhập vào dòng lệnh: wsdl /lingu:c# /n:TestDemo /out:d:/Temp/TestService.cs http://jm1.services.gmcc.net/ad/Services/AD.asmx?wsdl Cái này Ý nghĩa của dòng lệnh là: biên dịch địa chỉ dịch vụ cuối cùng và tạo tệp testservice trong thư mục tạm thời của ổ D. 3. Sao chép tệp cs được biên dịch bằng lệnh trên vào dự án của chúng tôi. Bạn có thể trực tiếp tạo một tệp mới trong mã dự án và gọi nó. Đăng mã được biên dịch từ dòng lệnh:

Sao chép mã mã như sau

Xem mã //------------------------------------------------------- --- -------------------------------- // // Mã này được tạo bởi dụng cụ. // Phiên bản thời gian chạy: 4.0.30319.225 // // Các thay đổi đối với tệp này có thể gây ra hành vi không chính xác và sẽ bị mất nếu // mã được tạo lại. // //--------------------------------------- ----------------------------------------------- // / / Mã nguồn này được tạo tự động bởi wsdl, Version=4.0.30319.1. // không gian tên Bingosoft.Module.SurveyQuestionnaire.DAL { sử dụng System.Diagnostics; sử dụng System.Xml.Serialization; sử dụng System.Web.Services.Protocols; Dữ liệu; /// [System.CodeDom.Compiler.GeneratedCodeAttribution("wsdl", "4.0.30319.1")] [System.Diagnostics.windowStepThroughAttribution()] [System.ComponentModel.DesignerCategoryAttribution("code")] [System.Web.Services.WebServiceBindingAttribution(Name="WebserviceForILookSoap", Namespace="http:// tempuri.org/")] lớp một phần công khai WebserviceForILook: System.Web.Services.Protocols.SoapHttpClientProtocol { riêng tư System.Threading.SendOrPostCallback GetRecordNumOperationCompleted; riêng tư System.Threading.SendOrPostCallback GetVoteListOperationCompleted; riêng tư System.Threading.SendOrPostCallback VoteOperationCompleted; System.Threading.SendOrPostCallback GetQuestionTaskListOperationCompleted; /// public WebserviceForILook() { this.Url = "http://st1.services.gmcc.net/qnaire/Services/WebserviceForILook.asmx" } /// < nhận xét/> sự kiện công khai GetRecordNumCompletedEventHandler GetRecordNumCompleted; sự kiện công khai GetVoteListCompletedEventHandler GetVoteListCompleted; /// sự kiện công khai VoteCompletedEventHandler VoteCompleted; /// sự kiện công khai GiveUpCompletedEventHandler GiveUpCompleted; /// sự kiện công khai GetQuestionTaskListCompletedEventHandler GetQuestionTaskListCompleted; / /> [System.Web.Services.Protocols.SoapDocumentMethodAttribution("http://tempuri.org/GetRecordNum",RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Sử dụng =System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public int[] GetRecordNum(string appcode, string userID) { object[] results = this.Invoke("GetRecordNum", new object[] { appcode, userID} ); return ((int[])(results[0])); } /// public System.IAsyncResult BeginGetRecordNum(chuỗi mã ứng dụng,chuỗi userID, System.AsyncCallback gọi lại, đối tượng asyncState) { trả về this.BeginInvoke("GetRecordNum", đối tượng mới[] { mã ứng dụng, userID}, gọi lại, asyncState); } /// public int[] EndGetRecordNum(System.IAsyncResult asyncResult) { đối tượng[] kết quả = this.EndInvoke(asyncResult); trả về ((int[])(results[0])); } /// public void GetRecordNumAsync(chuỗi mã ứng dụng, chuỗi userID) { this.GetRecordNumAsync(mã ứng dụng, userID, null); } /// public void GetRecordNumAsync(string appcode, string userID, object userState) { if ((this.GetRecordNumOperationCompleted == null)) { this.GetRecordNumOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetRecordNumOperationCompleted); } this.InvokeAsync("GetRecordNum", new object[] { appcode, userID}, this.GetRecordNumOperationCompleted, userState); } private void OnGetRecordNumOperationCompleted(object arg) { if ((this.GetRecordNumCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.GetRecordNumCompleted(this, new GetRecordNumCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/GetVoteList", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public System.Data.DataSet GetVoteList(string appcode, string userID) { object[] results = this.Invoke("GetVoteList", new object[] { appcode, userID}); trả về ((System.Data.DataSet)(results[0])); } /// public System.IAsyncResult BeginGetVoteList(string appcode, string userID, System.AsyncCallback callback, object asyncState) { trả về this.BeginInvoke("GetVoteList", new object[] { appcode, userID}, callback, asyncState); } /// public System.Data.DataSet EndGetVoteList(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); trả về ((System.Data.DataSet)(results[0])); } /// public void GetVoteListAsync(string appcode, string userID) { this.GetVoteListAsync(appcode, userID, null); } /// public void GetVoteListAsync(string appcode, string userID, object userState) { if ((this.GetVoteListOperationCompleted == null)) { this.GetVoteListOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetVoteListOperationCompleted); } this.InvokeAsync("GetVoteList", new object[] { appcode, userID}, this.GetVoteListOperationCompleted, userState); } private void OnGetVoteListOperationCompleted(object arg) { if ((this.GetVoteListCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.GetVoteListCompleted(this, new GetVoteListCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/Vote", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public bool Vote(chuỗi appcode, chuỗi userID, chuỗi qTaskID, chuỗi answer) { object[] results = this.Invoke("Vote", new object[] { appcode, userID, qTaskID, answer}); return ((bool)(results[0])); } /// public System.IAsyncResult BeginVote(string appcode, string userID, string qTaskID, string answer, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("Bình chọn", new object[] { appcode, userID, qTaskID, answer}, callback, asyncState); } /// public bool EndVote(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((bool)(results[0])); } /// public void VoteAsync(string appcode, string userID, string qTaskID, string answer) { this.VoteAsync(appcode, userID, qTaskID, answer, null); } /// public void VoteAsync(string appcode, string userID, string qTaskID, string answer, object userState) { if ((this.VoteOperationCompleted == null)) { this.VoteOperationCompleted = new System.Threading.SendOrPostCallback(this.OnVoteOperationCompleted); } this.InvokeAsync("Bình chọn", new object[] { appcode,userID, qTaskID, answer}, this.VoteOperationCompleted, userState); } private void OnVoteOperationCompleted(object arg) { if ((this.VoteCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.VoteCompleted(this, new VoteCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/GiveUp", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public bool GiveUp(chuỗi appcode, chuỗi userID, chuỗi qTaskID) { đối tượng[] kết quả = this.Invoke("GiveUp", đối tượng mới[] { mã ứng dụng, userID, qTaskID}); trả về ((bool)(results[0])); } /// public System.IAsyncResult BeginGiveUp(string appcode, string userID, string qTaskID, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("GiveUp", new object[] { appcode, userID, qTaskID}, callback, asyncState); } /// public bool EndGiveUp(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((bool)(results[0])); } /// public void GiveUpAsync(string appcode, string userID, string qTaskID) { this.GiveUpAsync(appcode, userID, qTaskID, null); } /// public void GiveUpAsync(string appcode, string userID, string qTaskID, object userState) { if ((this.GiveUpOperationCompleted == null)) { this.GiveUpOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGiveUpOperationCompleted); } this.InvokeAsync("GiveUp", new object[] { appcode, userID, qTaskID}, this.GiveUpOperationCompleted, userState); } private void OnGiveUpOperationCompleted(object arg) { if ((this.GiveUpCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); này.GiveUpCompleted(này, mới GiveUpCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/GetQuestionTaskList", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public System.Data.DataSet GetQuestionTaskList(chuỗi mã ứng dụng, chuỗi ID người dùng) { đối tượng[] kết quả = this.Invoke("GetQuestionTaskList", đối tượng mới[] { mã ứng dụng, ID người dùng}); trả về ((System.Data.DataSet)(results[0])); } /// public System.IAsyncResult BeginGetQuestionTaskList(string appcode, string userID, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("GetQuestionTaskList", new object[] { appcode, userID}, callback, asyncState); } /// public System.Data.DataSet EndGetQuestionTaskList(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((System.Data.DataSet)(results[0])); } /// public void GetQuestionTaskListAsync(string appcode, string userID) { this.GetQuestionTaskListAsync(appcode, userID, null); } /// public void GetQuestionTaskListAsync(string appcode, string userID, object userState) { if ((this.GetQuestionTaskListOperationCompleted == null)) { this.GetQuestionTaskListOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetQuestionTaskListOperationCompleted); } this.InvokeAsync("GetQuestionTaskList", new object[] { appcode, userID}, this.GetQuestionTaskListOperationCompleted, userState); } private void OnGetQuestionTaskListOperationCompleted(object arg) { if ((this.GetQuestionTaskListCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.GetQuestionTaskListCompleted(this, new GetQuestionTaskListCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// public new void CancelAsync(object userState) { base.CancelAsync(userState); } } /// [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] public delegate void GetRecordNumCompletedEventHandler(đối tượng người gửi, GetRecordNumCompletedEventArgs e); /// [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] [System.Diagnostics.windowStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class GetRecordNumCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal GetRecordNumCompletedEventArgs(object[] results, System.Exception exception, bool ruined, object userState) : base(exception, ruined, userState) { this.results = results; } /// public int[] Result { get { this.RaiseExceptionIfNecessary(); return ((int[])(this.results[0])); } } } /// [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] public delegate void GetVoteListCompletedEventHandler(object sender, GetVoteListCompletedEventArgs e); /// [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] [System.Diagnostics.windowStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class GetVoteListCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal GetVoteListCompletedEventArgs(object[] results, System.Exception exception, bool ruined, object userState): base(exception, ruined, userState) { this.results = results; } /// public System.Data.DataSet Result { get { this.RaiseExceptionIfNecessary(); return ((System.Data.DataSet)(this.results[0])); } } } /// [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] public delegate void VoteCompletedEventHandler(object sender, VoteCompletedEventArgs e); /// [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] [System.Diagnostics.windowStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class VoteCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; nội bộ VoteCompletedEventArgs(object[] results, System.Exception exception, bool ruined, object userState) : base(exception, ruined, userState) { this.results = results; } /// public bool Result { get { this.RaiseExceptionIfNecessary(); return ((bool)(this.results[0])); } } } /// [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] public delegate void GiveUpCompletedEventHandler(object sender, GiveUpCompletedEventArgs e); /// [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] [System.Diagnostics.windowStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class GiveUpCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal GiveUpCompletedEventArgs(object[] results, System.Exception exception, bool ruined, object userState) : base(exception, ruined, userState) { this.results = results; } /// public bool Result { get { this.RaiseExceptionIfNecessary(); return ((bool)(this.results[0])); } } } /// [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] public delegate void GetQuestionTaskListCompletedEventHandler(object sender, GetQuestionTaskListCompletedEventArgs e); /// [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] [System.Diagnostics.windowStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class GetQuestionTaskListCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; nội bộ GetQuestionTaskListCompletedEventArgs(object[] results, System.Exception exception, bool ruined, object userState) : base(exception, ruined, userState) { this.results = results; } /// public System.Data.DataSet Result { get { this.RaiseExceptionIfNecessary(); return ((System.Data.DataSet)(this.results[0])); } } } } 。CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] public delegate void GetQuestionTaskListCompletedEventHandler(object sender, GetQuestionTaskListCompletedEventArgs e); /// [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] [System.Diagnostics.windowStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class GetQuestionTaskListCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal GetQuestionTaskListCompletedEventArgs(object[] results, System.Exception exception, bool ruined, object userState): base(exception, ruined, userState) { this.results = results; } /// public System.Data.DataSet Result { get { this.RaiseExceptionIfNecessary(); return ((System.Data.DataSet)(this.results[0])); } } } } 。CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] public delegate void GetQuestionTaskListCompletedEventHandler(object sender, GetQuestionTaskListCompletedEventArgs e); /// [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] [System.Diagnostics.windowStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class GetQuestionTaskListCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal GetQuestionTaskListCompletedEventArgs(object[] results, System.Exception exception, bool ruined, object userState): base(exception, ruined, userState) { this.results = results; } /// public System.Data.DataSet Result { get { this.RaiseExceptionIfNecessary(); return ((System.Data.DataSet)(this.results[0])); } } } } 。

Cách 3: Sử dụng get và post của giao thức http. Đây là phương pháp linh hoạt nhất.

Sao chép mã mã như sau

Xem Mã bằng System; sử dụng System.Collections; sử dụng System.Net; sử dụng System.Xml; sử dụng không gian tên System.Xml.Serialization; /// Lớp sử dụng WebRequest/WebResponse để thực hiện lệnh gọi WebService /// public class WebServiceCaller { #zone Mẹo: Hướng dẫn sử dụng //webServices Các cuộc gọi Nhận và Đăng phải được hỗ trợ. Đoạn mã sau phải được thêm vào web.config // // // // // // //Gọi ví dụ: //Hashtable ht = new Hashtable(); //Hashtable là tập tham số được yêu cầu bởi webservice //ht.Add("str", "test" ); //ht.Add("b", "true"); //XmlDocument xx = WebSvcCaller.QuerySoapWebService("http://localhost:81/service.asmx", "HelloWorld", ht); (xx.OuterXml); #endzone ///

/// WebService cần hỗ trợ Post call /// public static XmlDocument QueryPostWebService(URL chuỗi, String MethodName, Hashtable Pars) { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL + "/" + MethodName = "POST"; biểu mẫu-urlencoded"; SetWebRequest(request); byte[] data = EncodePars(Pars); WriteRequestData(request, data); return ReadXmlResponse(request.GetResponse()); } /// /// WebService cần hỗ trợ Nhận cuộc gọi /// public static XmlDocument QueryGetWebService( URL chuỗi, Tên phương thức chuỗi, Phân tích có thể băm) { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL + "/" + MethodName + "?" + ParsToString(Pars)); request.Method = "GET" request.ContentType = "application/x-www-form-urlencoded"; (yêu cầu); trả về ReadXmlResponse(request.GetResponse()); } /// /// Lệnh gọi WebService chung (Xà phòng), tham số Pars là Tên tham số kiểu chuỗi và giá trị tham số /// public static XmlDocument QuerySoapWebService(String URL, String MethodName, Hashtable Pars) { if (_xmlNamespaces.ContainsKey(URL ) ) { return QuerySoapWebService(URL, MethodName, Pars, _xmlNamespaces[URL].ToString()); } else { return QuerySoapWebService(URL, MethodName, Pars, GetNamespace(URL)); } } riêng tư XmlDocument QuerySoapWebService(String URL, String MethodName, Hashtable Pars,string XmlNs) { _xmlNamespaces[URL] = XmlNs;//Không gian tên, không gian tên người dùng HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL); request.Method = "POST"; request.ContentType = "text/xml; charset=utf-8"; request.Headers.Add("SOAPAction", "\"" + XmlNs + (XmlNs.EndsWith("/") ? "" : "/") + MethodName + "\""); SetWebRequest(request); byte[] data = EncodeParsToSoap(Pars, XmlNs, MethodName); WriteRequestData(request, data); XmlDocument doc = new XmlDocument(), doc2 = new XmlDocument(); doc = ReadXmlResponse(request.GetResponse()); XmlNamespaceManager mgr = new XmlNamespaceManager(doc.NameTable); mgr.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/"); String RetXml = doc.SelectSingleNode("//soap:Body/*/*", mgr).InnerXml; doc2.LoadXml("" + RetXml + ""); AddDelaration(doc2); return doc2; } private static string GetNamespace(String URL) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL + "?WSDL"); SetWebRequest(request); WebResponse response = request.GetResponse(); StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8); XmlDocument doc = new XmlDocument(); doc.LoadXml(sr.ReadToEnd()); sr.Close(); trả về doc.SelectSingleNode("//@targetNamespace").Giá trị; } private static byte[] EncodeParsToSoap(Hashtable Pars, String XmlNs, String MethodName) { XmlDocument doc = new XmlDocument(); doc.LoadXml(""); AddDelaration(doc); //XmlElement soapBody = doc.createElement_x_x("soap", "Body", "http://schemas.xmlsoap.org/soap/envelope/"); XmlElement soapBody = doc.CreateElement("soap", "Body", "http://schemas.xmlsoap.org/soap/envelope/"); //XmlElement soapMethod = doc.createElement_x_x(MethodName); XmlElement soapMethod = doc.CreateElement(MethodName); soapMethod.SetAttribute("xmlns", XmlNs); foreach (chuỗi k trong Pars.Keys) { //XmlElement soapPar = doc.createElement_x_x(k); XmlElement soapPar = doc.CreateElement(k); soapPar.InnerXml = ObjectToSoapXml(Pars[k]); soapMethod.AppendChild(soapPar); } soapBody.AppendChild(soapMethod); doc.DocumentElement.AppendChild(soapBody); return Encoding.UTF8.GetBytes(doc.OuterXml); } private static string ObjectToSoapXml(object o) { XmlSerializer mySerializer = new XmlSerializer(o.GetType()); MemoryStream ms = new MemoryStream(); mySerializer.Serialize(ms, o); XmlDocument doc = new XmlDocument(); doc.LoadXml(Encoding.UTF8.GetString(ms.ToArray())); if (doc.DocumentElement != null) { return doc.DocumentElement.InnerXml; } else { return o.ToString(); } } /// /// Không có yêu cầu nào được gửi /// /// private static void SetWebRequest(HttpWebRequest request) { request.Credentials = CredentialCache.DefaultCredentials; request.Timeout = 10000; } private static void WriteRequestData(HttpWebRequest request, byte[] data) { request.ContentLength = data.Length; Stream writer = request.GetRequestStream(); writer.Write(data, 0, data.Length); writer.Close(); } private static byte[] EncodePars(Hashtable Pars) { return Encoding.UTF8.GetBytes(ParsToString(Pars)); } private static String ParsToString(Hashtable Pars) { StringBuilder sb = new StringBuilder(); foreach (chuỗi k trong Pars.Keys) { if (sb.Length > 0) { sb.Append("&"); } //sb.Append(HttpUtility.UrlEncode(k) + "=" + HttpUtility.UrlEncode(Pars[k].ToString())); } return sb.ToString(); } private static XmlDocument ReadXmlResponse(WebResponse response) { StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8); String retXml = sr.ReadToEnd(); sr.Close(); XmlDocument doc = new XmlDocument(); doc.LoadXml(retXml); return doc; } private static void AddDelaration(XmlDocument doc) { XmlDeclaration decl = doc.CreateXmlDeclaration("1.0", "utf-8", null); doc.InsertBefore(decl, doc.DocumentElement); } Hashtable tĩnh riêng _xmlNamespaces = Hashtable mới();//缓存xmlNamespace,避免重复调用GetNamespace } } 。GetType()); MemoryStream ms = new MemoryStream(); mySerializer.Serialize(ms, o); XmlDocument doc = new XmlDocument(); doc.LoadXml(Encoding.UTF8.GetString(ms.ToArray())); if (doc.DocumentElement != null) { return doc.DocumentElement.InnerXml; } else { return o.ToString(); } } /// /// Không có lỗi nào được phát hiện /// /// private static void SetWebRequest(HttpWebRequest request) { request.Credentials = CredentialCache.DefaultCredentials; request.Timeout = 10000; } private static void WriteRequestData(HttpWebRequest request, byte[] data) { request.ContentLength = data.Length; Stream writer = request.GetRequestStream(); writer.Write(data, 0, data.Length); writer.Close(); } private static byte[] EncodePars(Hashtable Pars) { return Encoding.UTF8.GetBytes(ParsToString(Pars)); } private static String ParsToString(Hashtable Pars) { StringBuilder sb = new StringBuilder(); foreach (string k in Pars.Keys) { if (sb.Length > 0) { sb.Append("&"); } //sb.Append(HttpUtility.UrlEncode(k) + "=" + HttpUtility.UrlEncode(Pars[k].ToString())); } return sb.ToString(); } private static XmlDocument ReadXmlResponse(WebResponse response) { StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8); String retXml = sr.ReadToEnd(); sr.Close(); XmlDocument doc = new XmlDocument(); doc.LoadXml(retXml); return doc; } private static void AddDelaration(XmlDocument doc) { XmlDeclaration decl = doc.CreateXmlDeclaration("1.0", "utf-8", null); doc.InsertBefore(decl, doc.DocumentElement); } private static Hashtable _xmlNamespaces = new Hashtable();//Không có xmlNamespace, hãy sử dụng GetNamespace } } 。GetType()); MemoryStream ms = new MemoryStream(); mySerializer.Serialize(ms, o); XmlDocument doc = new XmlDocument(); doc.LoadXml(Encoding.UTF8.GetString(ms.ToArray())); if (doc.DocumentElement != null) { return doc.DocumentElement.InnerXml; } else { return o.ToString(); } } /// /// Không có lỗi nào được phát hiện /// /// private static void SetWebRequest(HttpWebRequest request) { request.Credentials = CredentialCache.DefaultCredentials; request.Timeout = 10000; } private static void WriteRequestData(HttpWebRequest request, byte[] data) { request.ContentLength = data.Length; Stream writer = request.GetRequestStream(); writer.Write(data, 0, data.Length); writer.Close(); } private static byte[] EncodePars(Hashtable Pars) { return Encoding.UTF8.GetBytes(ParsToString(Pars)); } private static String ParsToString(Hashtable Pars) { StringBuilder sb = new StringBuilder(); foreach (string k in Pars.Keys) { if (sb.Length > 0) { sb.Append("&"); } //sb.Append(HttpUtility.UrlEncode(k) + "=" + HttpUtility.UrlEncode(Pars[k].ToString())); } return sb.ToString(); } private static XmlDocument ReadXmlResponse(WebResponse response) { StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8); String retXml = sr.ReadToEnd(); sr.Close(); XmlDocument doc = new XmlDocument(); doc.LoadXml(retXml); return doc; } private static void AddDelaration(XmlDocument doc) { XmlDeclaration decl = doc.CreateXmlDeclaration("1.0", "utf-8", null); doc.InsertBefore(decl, doc.DocumentElement); } private static Hashtable _xmlNamespaces = new Hashtable();//Không có xmlNamespace, hãy sử dụng GetNamespace } } 。ToString(); } } /// /// Phương thức khởi tạo và phương thức thực thi /// /// private static void SetWebRequest(HttpWebRequest request) { request.Credentials = CredentialCache.DefaultCredentials; request.Timeout = 10000; } private static void WriteRequestData(HttpWebRequest request, byte[] data) { request.ContentLength = data.Length; Stream writer = request.GetRequestStream(); writer.Write(data, 0, data.Length); writer.Close(); } private static byte[] EncodePars(Hashtable Pars) { return Encoding.UTF8.GetBytes(ParsToString(Pars)); } private static String ParsToString(Hashtable Pars) { StringBuilder sb = new StringBuilder(); foreach (chuỗi k trong Pars.Keys) { if (sb.Length > 0) { sb.Append("&"); } //sb.Append(HttpUtility.UrlEncode(k) + "=" + HttpUtility.UrlEncode(Pars[k].ToString())); } return sb.ToString(); } private static XmlDocument ReadXmlResponse(WebResponse response) { StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8); String retXml = sr.ReadToEnd(); sr.Close(); XmlDocument doc = new XmlDocument(); doc.LoadXml(retXml); return doc; } void tĩnh riêng AddDelaration(XmlDocument doc) { XmlDeclaration decl = doc.CreateXmlDeclaration("1.0", "utf-8", null); doc.InsertBefore(decl, doc.DocumentElement); } Hashtable tĩnh riêng _xmlNamespaces = Hashtable mới();//缓存xmlNamespace,避免重复调用GetNamespace } } 。ToString(); } } /// /// Phương thức khởi tạo và phương thức thực thi /// /// private static void SetWebRequest(HttpWebRequest request) { request.Credentials = CredentialCache.DefaultCredentials; request.Timeout = 10000; } private static void WriteRequestData(HttpWebRequest request, byte[] data) { request.ContentLength = data.Length; Stream writer = request.GetRequestStream(); writer.Write(data, 0, data.Length); writer.Close(); } private static byte[] EncodePars(Hashtable Pars) { return Encoding.UTF8.GetBytes(ParsToString(Pars)); } private static String ParsToString(Hashtable Pars) { StringBuilder sb = new StringBuilder(); foreach (chuỗi k trong Pars.Keys) { if (sb.Length > 0) { sb.Append("&"); } //sb.Append(HttpUtility.UrlEncode(k) + "=" + HttpUtility.UrlEncode(Pars[k].ToString())); } return sb.ToString(); } private static XmlDocument ReadXmlResponse(WebResponse response) { StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8); String retXml = sr.ReadToEnd(); sr.Close(); XmlDocument doc = new XmlDocument(); doc.LoadXml(retXml); return doc; } void tĩnh riêng AddDelaration(XmlDocument doc) { XmlDeclaration decl = doc.CreateXmlDeclaration("1.0", "utf-8", null); doc.InsertBefore(decl, doc.DocumentElement); } Hashtable tĩnh riêng _xmlNamespaces = Hashtable mới();//缓存xmlNamespace,避免重复调用GetNamespace } } 。ToString())); } return sb.ToString(); } private static XmlDocument ReadXmlResponse(WebResponse response) { StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8); String retXml = sr.ReadToEnd(); sr.Close(); XmlDocument doc = new XmlDocument(); doc.LoadXml(retXml); return doc; } private static void AddDelaration(XmlDocument doc) { XmlDeclaration decl = doc.CreateXmlDeclaration("1.0", "utf-8", null); doc.InsertBefore(decl, doc.DocumentElement); } Hashtable tĩnh riêng _xmlNamespaces = Hashtable mới();//缓存xmlNamespace,避免重复调用GetNamespace } } 。ToString())); } return sb.ToString(); } private static XmlDocument ReadXmlResponse(WebResponse response) { StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8); String retXml = sr.ReadToEnd(); sr.Close(); XmlDocument doc = new XmlDocument(); doc.LoadXml(retXml); return doc; } private static void AddDelaration(XmlDocument doc) { XmlDeclaration decl = doc.CreateXmlDeclaration("1.0", "utf-8", null); doc.InsertBefore(decl, doc.DocumentElement); } Hashtable tĩnh riêng _xmlNamespaces = Hashtable mới();//缓存xmlNamespace,避免重复调用GetNamespace } } 。

 

Cuối cùng, bài viết này về tóm tắt và phân tích chuyên sâu về dịch vụ web gọi .net kết thúc ở đây. Nếu bạn muốn biết thêm về tóm tắt và phân tích chuyên sâu về dịch vụ web gọi .net, vui lòng tìm kiếm bài viết CFSDN hoặc tiếp tục duyệt các bài viết liên quan. Tôi hy vọng tất cả các bạn sẽ ủng hộ blog của tôi trong tương lai! .

30 4 0
qq735679552
Hồ sơ

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá taxi Didi miễn phí
Phiếu giảm giá taxi Didi
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress