加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

.net 调用webservice 总结

发布时间:2020-12-16 23:39:47 所属栏目:安全 来源:网络整理
导读:我们都知道,调用webserivice 最简单的方法就是在 "引用" 那里点击右键,然后选择"引用web服务",再输入服务地址。 确定后,会生成一个app.config 里面就会自动生成了一些配置信息。 现在正在做的这个项目就不能这么干。后来经过一番搜索,就找出另外几种动

我们都知道,调用webserivice 最简单的方法就是在 "引用" 那里点击右键,然后选择"引用web服务",再输入服务地址。

确定后,会生成一个app.config 里面就会自动生成了一些配置信息。

现在正在做的这个项目就不能这么干。后来经过一番搜索,就找出另外几种动态调用webservice 的方法。

废话少说,下面是webservice 代码

View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace TestWebService
{
    /// <summary>
    /// Service1 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/",Description="我的Web服务")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
    // [System.Web.Script.Services.ScriptService]
    public class TestWebService : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld()
        {
            return "测试Hello World";
        }

        [WebMethod]
        public string Test()
        {
            return "测试Test";
        }
      
        [WebMethod(CacheDuration = 60,Description = "测试")]
        public List<String> GetPersons()
        {
            List<String> list = new List<string>();
            list.Add("测试一");
            list.Add("测试二");
            list.Add("测试三");
            return list;
        }  

    }


}

动态调用示例:

方法一:

看到很多动态调用WebService都只是动态调用地址而已,下面发一个不光是根据地址调用,方法名也可以自己指定的,主要原理是根据指定的WebService地址的WSDL,然后解析模拟生成一个代理类,通过反射调用里面的方法

View Code
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Collections;
using System.Web;
using System.Net;
using System.Reflection;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Web.Services;
using System.Text;
using System.Web.Services.Description;
using System.Web.Services.Protocols;
using System.Xml.Serialization;
using System.Windows.Forms;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            WebClient client = new WebClient();
            String url = "http://localhost:3182/Service1.asmx?WSDL";//这个地址可以写在Config文件里面,这里取出来就行了.在原地址后面加上: ?WSDL
            Stream stream = client.OpenRead(url);
            ServiceDescription description = ServiceDescription.Read(stream);

            ServiceDescriptionImporter importer = new ServiceDescriptionImporter();//创建客户端代理代理类。

            importer.ProtocolName = "Soap"; //指定访问协议。
            importer.Style = ServiceDescriptionImportStyle.Client; //生成客户端代理。
            importer.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync;

            importer.AddServiceDescription(description,null,null); //添加WSDL文档。

            CodeNamespace nmspace = new CodeNamespace(); //命名空间
            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";//输出程序集的名称
            parameter.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");//加载前面生成的程序集
            Type t = asm.GetType("TestWebService.TestWebService");

            object o = Activator.CreateInstance(t);
            MethodInfo method = t.GetMethod("GetPersons");//GetPersons是服务端的方法名称,你想调用服务端的什么方法都可以在这里改,最好封装一下

            String[] item = (String[])method.Invoke(o,null);
            //注:method.Invoke(o,null)返回的是一个Object,如果你服务端返回的是DataSet,这里也是用(DataSet)method.Invoke(o,null)转一下就行了,method.Invoke(0,null)这里的null可以传调用方法需要的参数,string[]形式的
            foreach (string str in item)
                Console.WriteLine(str);

            //上面是根据WebService地址,模似生成一个代理类,如果你想看看生成的代码文件是什么样子,可以用以下代码保存下来,默认是保存在bin目录下面
            TextWriter writer = File.CreateText("MyTest.cs"); 
            provider.GenerateCodeFromCompileUnit(unit,writer,null);
            writer.Flush();
            writer.Close();
        } 
    }
}

在网上找了一个更为详细的

http://www.voidcn.com/article/p-kthiqwfl-qo.html

方法二:利用 wsdl.exe生成webservice代理类:

根据提供的wsdl生成webservice代理类,然后在代码里引用这个类文件。

步骤:1、在开始菜单找到 Microsoft Visual Studio 2010 下面的Visual Studio Tools , 点击Visual Studio 命令提示(2010),打开命令行。

2、 在命令行中输入: wsdl /language:c# /n:TestDemo /out:d:/Temp/TestService.cs http://jm1.services.gmcc.net/ad/Services/AD.asmx?wsdl

这句命令行的意思是:对最后面的服务地址进行编译,在D盘temp 目录下生成testservice文件。

3、 把上面命令编译后的cs文件,复制到我们项目中,在项目代码中可以直接new 一个出来后,可以进行调用。

贴出由命令行编译出来的代码:

View Code
//------------------------------------------------------------------------------
// <auto-generated>
//     此代码由工具生成。
//     运行时版本:4.0.30319.225
//
//     对此文件的更改可能会导致不正确的行为,并且如果
//     重新生成代码,这些更改将会丢失。
// </auto-generated>
//------------------------------------------------------------------------------

// 
// 此源代码由 wsdl 自动生成,Version=4.0.30319.1。
// 
namespace Bingosoft.Module.SurveyQuestionnaire.DAL {
    using System;
    using System.Diagnostics;
    using System.Xml.Serialization;
    using System.ComponentModel;
    using System.Web.Services.Protocols;
    using System.Web.Services;
    using System.Data;
    
    
    /// <remarks/>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl","4.0.30319.1")]
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Web.Services.WebServiceBindingAttribute(Name="WebserviceForILookSoap",Namespace="http://tempuri.org/")]
    public partial class WebserviceForILook : System.Web.Services.Protocols.SoapHttpClientProtocol {
        
        private System.Threading.SendOrPostCallback GetRecordNumOperationCompleted;
        
        private System.Threading.SendOrPostCallback GetVoteListOperationCompleted;
        
        private System.Threading.SendOrPostCallback VoteOperationCompleted;
        
        private System.Threading.SendOrPostCallback GiveUpOperationCompleted;
        
        private System.Threading.SendOrPostCallback GetQuestionTaskListOperationCompleted;
        
        /// <remarks/>
        public WebserviceForILook() {
            this.Url = "http://st1.services.gmcc.net/qnaire/Services/WebserviceForILook.asmx";
        }
        
        /// <remarks/>
        public event GetRecordNumCompletedEventHandler GetRecordNumCompleted;
        
        /// <remarks/>
        public event GetVoteListCompletedEventHandler GetVoteListCompleted;
        
        /// <remarks/>
        public event VoteCompletedEventHandler VoteCompleted;
        
        /// <remarks/>
        public event GiveUpCompletedEventHandler GiveUpCompleted;
        
        /// <remarks/>
        public event GetQuestionTaskListCompletedEventHandler GetQuestionTaskListCompleted;
        
        /// <remarks/>
        [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/GetRecordNum",RequestNamespace="http://tempuri.org/",ResponseNamespace="http://tempuri.org/",Use=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]));
        }
        
        /// <remarks/>
        public System.IAsyncResult BeginGetRecordNum(string appcode,string userID,System.AsyncCallback callback,object asyncState) {
            return this.BeginInvoke("GetRecordNum",userID},callback,asyncState);
        }
        
        /// <remarks/>
        public int[] EndGetRecordNum(System.IAsyncResult asyncResult) {
            object[] results = this.EndInvoke(asyncResult);
            return ((int[])(results[0]));
        }
        
        /// <remarks/>
        public void GetRecordNumAsync(string appcode,string userID) {
            this.GetRecordNumAsync(appcode,userID,null);
        }
        
        /// <remarks/>
        public void GetRecordNumAsync(string appcode,object userState) {
            if ((this.GetRecordNumOperationCompleted == null)) {
                this.GetRecordNumOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetRecordNumOperationCompleted);
            }
            this.InvokeAsync("GetRecordNum",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));
            }
        }
        
        /// <remarks/>
        [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/GetVoteList",ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
        public System.Data.DataSet GetVoteList(string appcode,string userID) {
            object[] results = this.Invoke("GetVoteList",userID});
            return ((System.Data.DataSet)(results[0]));
        }
        
        /// <remarks/>
        public System.IAsyncResult BeginGetVoteList(string appcode,object asyncState) {
            return this.BeginInvoke("GetVoteList",asyncState);
        }
        
        /// <remarks/>
        public System.Data.DataSet EndGetVoteList(System.IAsyncResult asyncResult) {
            object[] results = this.EndInvoke(asyncResult);
            return ((System.Data.DataSet)(results[0]));
        }
        
        /// <remarks/>
        public void GetVoteListAsync(string appcode,string userID) {
            this.GetVoteListAsync(appcode,null);
        }
        
        /// <remarks/>
        public void GetVoteListAsync(string appcode,object userState) {
            if ((this.GetVoteListOperationCompleted == null)) {
                this.GetVoteListOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetVoteListOperationCompleted);
            }
            this.InvokeAsync("GetVoteList",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.UserState));
            }
        }
        
        /// <remarks/>
        [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/Vote",ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
        public bool Vote(string appcode,string qTaskID,string answer) {
            object[] results = this.Invoke("Vote",qTaskID,answer});
            return ((bool)(results[0]));
        }
        
        /// <remarks/>
        public System.IAsyncResult BeginVote(string appcode,string answer,object asyncState) {
            return this.BeginInvoke("Vote",answer},asyncState);
        }
        
        /// <remarks/>
        public bool EndVote(System.IAsyncResult asyncResult) {
            object[] results = this.EndInvoke(asyncResult);
            return ((bool)(results[0]));
        }
        
        /// <remarks/>
        public void VoteAsync(string appcode,string answer) {
            this.VoteAsync(appcode,answer,null);
        }
        
        /// <remarks/>
        public void VoteAsync(string appcode,object userState) {
            if ((this.VoteOperationCompleted == null)) {
                this.VoteOperationCompleted = new System.Threading.SendOrPostCallback(this.OnVoteOperationCompleted);
            }
            this.InvokeAsync("Vote",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.UserState));
            }
        }
        
        /// <remarks/>
        [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/GiveUp",ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
        public bool GiveUp(string appcode,string qTaskID) {
            object[] results = this.Invoke("GiveUp",qTaskID});
            return ((bool)(results[0]));
        }
        
        /// <remarks/>
        public System.IAsyncResult BeginGiveUp(string appcode,object asyncState) {
            return this.BeginInvoke("GiveUp",qTaskID},asyncState);
        }
        
        /// <remarks/>
        public bool EndGiveUp(System.IAsyncResult asyncResult) {
            object[] results = this.EndInvoke(asyncResult);
            return ((bool)(results[0]));
        }
        
        /// <remarks/>
        public void GiveUpAsync(string appcode,string qTaskID) {
            this.GiveUpAsync(appcode,null);
        }
        
        /// <remarks/>
        public void GiveUpAsync(string appcode,object userState) {
            if ((this.GiveUpOperationCompleted == null)) {
                this.GiveUpOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGiveUpOperationCompleted);
            }
            this.InvokeAsync("GiveUp",this.GiveUpOperationCompleted,userState);
        }
        
        private void OnGiveUpOperationCompleted(object arg) {
            if ((this.GiveUpCompleted != null)) {
                System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
                this.GiveUpCompleted(this,new GiveUpCompletedEventArgs(invokeArgs.Results,invokeArgs.UserState));
            }
        }
        
        /// <remarks/>
        [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/GetQuestionTaskList",ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
        public System.Data.DataSet GetQuestionTaskList(string appcode,string userID) {
            object[] results = this.Invoke("GetQuestionTaskList",userID});
            return ((System.Data.DataSet)(results[0]));
        }
        
        /// <remarks/>
        public System.IAsyncResult BeginGetQuestionTaskList(string appcode,object asyncState) {
            return this.BeginInvoke("GetQuestionTaskList",asyncState);
        }
        
        /// <remarks/>
        public System.Data.DataSet EndGetQuestionTaskList(System.IAsyncResult asyncResult) {
            object[] results = this.EndInvoke(asyncResult);
            return ((System.Data.DataSet)(results[0]));
        }
        
        /// <remarks/>
        public void GetQuestionTaskListAsync(string appcode,string userID) {
            this.GetQuestionTaskListAsync(appcode,null);
        }
        
        /// <remarks/>
        public void GetQuestionTaskListAsync(string appcode,object userState) {
            if ((this.GetQuestionTaskListOperationCompleted == null)) {
                this.GetQuestionTaskListOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetQuestionTaskListOperationCompleted);
            }
            this.InvokeAsync("GetQuestionTaskList",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.UserState));
            }
        }
        
        /// <remarks/>
        public new void CancelAsync(object userState) {
            base.CancelAsync(userState);
        }
    }
    
    /// <remarks/>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl","4.0.30319.1")]
    public delegate void GetRecordNumCompletedEventHandler(object sender,GetRecordNumCompletedEventArgs e);
    
    /// <remarks/>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl","4.0.30319.1")]
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    public partial class GetRecordNumCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
        
        private object[] results;
        
        internal GetRecordNumCompletedEventArgs(object[] results,System.Exception exception,bool cancelled,object userState) : 
                base(exception,cancelled,userState) {
            this.results = results;
        }
        
        /// <remarks/>
        public int[] Result {
            get {
                this.RaiseExceptionIfNecessary();
                return ((int[])(this.results[0]));
            }
        }
    }
    
    /// <remarks/>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl","4.0.30319.1")]
    public delegate void GetVoteListCompletedEventHandler(object sender,GetVoteListCompletedEventArgs e);
    
    /// <remarks/>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl","4.0.30319.1")]
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    public partial class GetVoteListCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
        
        private object[] results;
        
        internal GetVoteListCompletedEventArgs(object[] results,userState) {
            this.results = results;
        }
        
        /// <remarks/>
        public System.Data.DataSet Result {
            get {
                this.RaiseExceptionIfNecessary();
                return ((System.Data.DataSet)(this.results[0]));
            }
        }
    }
    
    /// <remarks/>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl","4.0.30319.1")]
    public delegate void VoteCompletedEventHandler(object sender,VoteCompletedEventArgs e);
    
    /// <remarks/>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl","4.0.30319.1")]
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    public partial class VoteCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
        
        private object[] results;
        
        internal VoteCompletedEventArgs(object[] results,userState) {
            this.results = results;
        }
        
        /// <remarks/>
        public bool Result {
            get {
                this.RaiseExceptionIfNecessary();
                return ((bool)(this.results[0]));
            }
        }
    }
    
    /// <remarks/>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl","4.0.30319.1")]
    public delegate void GiveUpCompletedEventHandler(object sender,GiveUpCompletedEventArgs e);
    
    /// <remarks/>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl","4.0.30319.1")]
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    public partial class GiveUpCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
        
        private object[] results;
        
        internal GiveUpCompletedEventArgs(object[] results,"4.0.30319.1")]
    public delegate void GetQuestionTaskListCompletedEventHandler(object sender,GetQuestionTaskListCompletedEventArgs e);
    
    /// <remarks/>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl","4.0.30319.1")]
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    public partial class GetQuestionTaskListCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
        
        private object[] results;
        
        internal GetQuestionTaskListCompletedEventArgs(object[] results,userState) {
            this.results = results;
        }
        
        /// <remarks/>
        public System.Data.DataSet Result {
            get {
                this.RaiseExceptionIfNecessary();
                return ((System.Data.DataSet)(this.results[0]));
            }
        }
    }
}

更为详细的可以参见:http://www.voidcn.com/article/p-drlofvnv-dn.html

方法三:利用http 协议的get 和post

这是最为灵活的方法。

View Code

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读