动态WebService方法

时间:2024-12-17 13:06:38

【转】

调用Webservice的方法一般是通过右击项目--》添加服务引用--》输入Webservice地址--》前往--》确定,这样可以顺利调用服,但是需要注意的一点是:如果上面的方法是在非启动项项目(比如某个类库)中添加的,在该项目下会自动生成一个app.config文件,而在主配置文件web.config中并没有自动添加上该webservice的标记,这样运行会出现错误,说找不到配置信息等等……所有还需要把app.config中的<system.serviceModel>……</system.serviceModel>这段配置添加到web.config的<configuration>……</configuration>标记中,这样运行就不会出问题了。如果以后服务地址发生了变化,也只需要修改web.config中的地址就行了。

  如果你觉得上面的方法含麻烦的话,你可以选择下面的方法:动态WebService方法。需要写一个底层解析Webservice服务地址的方法,然后调用就可以,很方便。服务地址你可以配置到web.config中,也可以保存到数据库中,随你了……

  下面通过一个判断腾讯QQ在线状态的例子说明一下动态WebService的方法。

腾讯QQ在线状态WEB 服务:http://webservice.webxml.com.cn/webservices/qqOnlineWebService.asmx

  方法:qqCheckOnline 获得腾讯QQ在线状态

  输入参数:QQ号码 String,默认QQ号码:8698053。返回数据:String,Y = 在线;N = 离线;E = QQ号码错误;A = 商业用户验证失败;V = 免费用户超过数量

using System;
using System.Collections;
using System.Reflection;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Web.Services.Description;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Net;
using System.Web;

namespace Kayang.WebService
{
    /// <summary>
    /// WebServiceProxy 的摘要说明。
    /// </summary>
    public sealed class WebServiceProxy
    {
        private static Hashtable _assenblyCache = null;  //缓存提高效率
        public WebServiceProxy()
        {
        }
        //url:服务地址
     //methodname:方法名字
         //args:方法的参数
        public static object InvokeWebservice(string url, string nsClassName, string methodname, params object[] args)
        {
            , args);
        }
        public static object InvokeWebservice(string url, string nsClassName, string methodname, int timeout, params object[] args)
        {
             && args[] is ArrayList)
            {
                args = (args[] as ArrayList).ToArray();
            }
            try
            {
                int li = nsClassName.LastIndexOf('.');
                 ? , li));

                Assembly assembly;
                if (_assenblyCache == null)
                {
                    _assenblyCache = new Hashtable();
                }
                if (_assenblyCache.ContainsKey(url.ToUpper()))
                {
                    assembly = (Assembly)_assenblyCache[url.ToUpper()];
                }
                else
                {
                    System.Net.WebClient wc = new System.Net.WebClient();
                    System.IO.Stream stream = wc.OpenRead(url + "?WSDL");
                    //Configuration.SoapEnvelopeProcessingElement se = new Configuration.SoapEnvelopeProcessingElement();
                    //se.ReadTimeout = 15000;

                    ServiceDescription sd = ServiceDescription.Read(stream);
                    ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();
                    sdi.AddServiceDescription(sd, "", "");
                    CodeNamespace cn = new CodeNamespace(@namespace);
                    CodeCompileUnit ccu = new CodeCompileUnit();
                    ccu.Namespaces.Add(cn);
                    sdi.Import(cn, ccu);

                    Microsoft.CSharp.CSharpCodeProvider csc = new Microsoft.CSharp.CSharpCodeProvider();
                    ICodeCompiler icc = csc.CreateCompiler();
                    CompilerParameters cplist = new CompilerParameters();
                    cplist.GenerateExecutable = false;
                    cplist.GenerateInMemory = true;
                    cplist.ReferencedAssemblies.Add("System.dll");
                    cplist.ReferencedAssemblies.Add("System.XML.dll");
                    cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
                    cplist.ReferencedAssemblies.Add("System.Data.dll");
                    CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu);
                    if (true == cr.Errors.HasErrors)
                    {
                        System.Text.StringBuilder sb = new System.Text.StringBuilder();
                        foreach (CompilerError ce in cr.Errors)
                        {
                            sb.Append(ce.ToString());
                            sb.Append(System.Environment.NewLine);
                        }
                        throw new Exception(sb.ToString());
                    }
                    assembly = cr.CompiledAssembly;
                    _assenblyCache[url.ToUpper()] = assembly;
                }
                Type t = null;
                if (String.IsNullOrEmpty(nsClassName))
                {
                    t = assembly.GetTypes()[];
                }
                else
                {
                    t = assembly.GetType(nsClassName, true, true);
                }
                MethodInfo mi = null;
                if (String.IsNullOrEmpty(methodname))
                {
                    mi = t.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance)[];
                }
                else
                {
                    mi = t.GetMethod(methodname);
                }
                SoapHttpClientProtocol obj = Activator.CreateInstance(t) as SoapHttpClientProtocol;
                SetCookie(url, obj);
                //obj.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
                obj.Timeout = timeout;
                return mi.Invoke(obj, args);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));
            }
        }

        /// <summary>
        /// 传入Cookie,使对方可以使用当前Session
        /// By 黄正 2009-12-6
        /// </summary>
        /// <param name="url"></param>
        /// <param name="obj"></param>
        private static void SetCookie(string url, SoapHttpClientProtocol obj)
        {
            HttpContext ctx = HttpContext.Current;
            if (ctx != null)
            {
                CookieContainer cc = new CookieContainer();
                foreach (string cookieName in ctx.Request.Cookies.AllKeys)
                {
                    cc.SetCookies(new Uri(url), cookieName + "=" + ctx.Request.Cookies[cookieName].Value);
                }
                //req.Headers.Add(HttpRequestHeader.Cookie, Request.Headers["Cookie"]);
                obj.CookieContainer = cc;
            }
        }
    }
}

调用:

string url = "http://webservice.webxml.com.cn/webservices/qqOnlineWebService.asmx";
string @namespace="";
string methodname = "qqCheckOnline";//需要调用的webservice中的方法
";//QQ号码
string result = WebService.WebServiceProxy.InvokeWebservice(url, @namespace, methodname, Invoke).ToString();