C# 编写微服务

C# 服务端接口代码:

    ///

    /// WebService1 的摘要说明  服务应用程序

    ///

    [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 WebService1 : System.Web.Services.WebService

    {

        [WebMethod]

        public string HelloWorld()

        {

            return "Hello World";

        }

        ///

        /// 调用方法:var retupobj = Common.UpLoadData.InvokeWebServiceEx("http://192.168.6.115/WEBSERVERtest/WebService1.asmx", "AddInt",new object[] {2,3});

        ///

        ///

        ///

        ///

        [WebMethod]

        public int AddInt(int A, int B)

        {

            return A + B + 100 - 10;

        }

        [WebMethod]

        public string HelloWorld1(string xl)

        {

            return xl + "88888888";

        }

        [WebMethod]

        public string SelectBaseInfo(string typeOrd)

        {

            WebApplication1.SelData.SelectBaseInfo SBI = new WebApplication1.SelData.SelectBaseInfo();

            return SBI.GetBaseInfo(typeOrd);

        }

    }

客户端调用接口服务代码:

public class WebServiceHelper

    {

        /// < summary>          

        /// 动态调用web服务        

        /// < /summary>         

        /// < param name="url">WSDL服务地址< /param>

        /// < param name="methodname">方法名< /param>          

        /// < param name="args">参数< /param>          

        /// < returns>< /returns>         

        public static object InvokeWebService(string url,string nameSpace, string methodname, object[] args)

        {

            return WebServiceHelper.InvokeWebService(url,nameSpace, null, methodname, args);

        }

        /// < summary>         

        /// 动态调用web服务

        /// < /summary>         

        /// < param name="url">WSDL服务地址< /param>

        /// < param name="classname">类名< /param> 

        /// < param name="methodname">方法名< /param> 

        /// < param name="args">参数< /param>

        /// < returns>< /returns>

        public static object InvokeWebService(string url,string nameSpace, string classname, string methodname, object[] args)

        {

            if ((classname == null) || (classname == ""))

            {

                classname = WebServiceHelper.GetWsClassName(url);

            }

            try

            {                   //获取WSDL  

                WebClient wc = new WebClient();

                Stream stream = wc.OpenRead(url + "?WSDL");

                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);

                CSharpCodeProvider icc = new CSharpCodeProvider();

                //设定编译参数                

                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 (System.CodeDom.Compiler.CompilerError ce in cr.Errors)

                    {

                        sb.Append(ce.ToString());

                        sb.Append(System.Environment.NewLine);

                    }

                    throw new Exception(sb.ToString());

                }

                //生成代理实例,并调用方法  

                System.Reflection.Assembly assembly = cr.CompiledAssembly;

                Type t = assembly.GetType(nameSpace + "." + classname, true, true);

                FieldInfo[] arry = t.GetFields();

                object obj = Activator.CreateInstance(t);

               

                System.Reflection.MethodInfo mi = t.GetMethod(methodname);

                return mi.Invoke(obj, args);

                // PropertyInfo propertyInfo = type.GetProperty(propertyname);    

                //return propertyInfo.GetValue(obj, null);

            }

            catch (Exception ex)

            {

                throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));

            }

        }

        private static string GetWsClassName(string wsUrl)

        {

            string[] parts = wsUrl.Split('/');

            string[] pps = parts[parts.Length - 1].Split('.');

            return pps[0];

        }

    }

    ///

    /// 连接WebService接口

    ///

    public static class WebServiceHelper2

    {

        private static IList<Hashtable> _lstServer = new List<Hashtable>();

        private static string GetWsClassName(string wsUrl)

        {

            string[] parts = wsUrl.Split(new char[] { '/' });

            return parts[parts.Length - 1].Split(new char[] { '.' })[0];

        }

        public static object InvokeWebService(string Url, string MethodName, object[] Args, string Date, [Optional, DefaultParameterValue(false)] bool IsThrowException)

        {

            if (_lstServer.Count > 0)

            {

                if (string.IsNullOrEmpty(Date))

                {

                    Date = DateTime.Now.ToString("yyyy-MM-dd");

                }

                IEnumerable<Hashtable> ie = _lstServer.Where<Hashtable>(delegate(Hashtable d)

                {

                    return d["date"].ToString() == Date;

                });

                if (ie.Count<Hashtable>() > 0)

                {

                    _lstServer = ie.ToList<Hashtable>();

                }

                else

                {

                    _lstServer = new List<Hashtable>();

                }

            }

            return InvokeWebServiceEx(Url, MethodName, Args, Date, IsThrowException, "", "");

        }

        private static object InvokeWebServiceEx(string Url, string MethodName, object[] Args, string Date, [Optional, DefaultParameterValue(false)] bool IsThrowException, [Optional, DefaultParameterValue("")] string UrlUser, [Optional, DefaultParameterValue("")] string UrlUserPwd)

        {

            if (string.IsNullOrEmpty(Date))

            {

                Date = DateTime.Now.ToString("yyyy-MM-dd");

            }

            string @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling";

            string ClassName = "";

            switch (ClassName)

            {

                case null:

                case "":

                    ClassName = GetWsClassName(Url);

                    break;

            }

            try

            {

                object obj = null;

                MethodInfo mi = null;

                Hashtable htObject = _lstServer.FirstOrDefault<Hashtable>(delegate(Hashtable d)

                {

                    return (d["url"].ToString() == Url) && (d["methodname"].ToString() == MethodName);

                });

                if (htObject != null)

                {

                    obj = htObject["obj"];

                    mi = htObject["mi"] as MethodInfo;

                }

                else

                {

                    WebClient wc = new WebClient();

                    ServiceDescription sd = ServiceDescription.Read(wc.OpenRead(Url + "?WSDL"));

                    ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();

                    sdi.AddServiceDescription(sd, "", "");

                    CodeNamespace cn = new CodeNamespace(@namespace);

                    CodeCompileUnit ccu = new CodeCompileUnit();

                    ccu.Namespaces.Add(cn);

                    sdi.Import(cn, ccu);

                    CSharpCodeProvider icc = new CSharpCodeProvider();

                    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, new CodeCompileUnit[] { ccu });

                    if (cr.Errors.HasErrors)

                    {

                        StringBuilder sb = new StringBuilder();

                        foreach (CompilerError ce in cr.Errors)

                        {

                            sb.Append(ce.ToString());

                            sb.Append(Environment.NewLine);

                        }

                        throw new Exception(sb.ToString());

                    }

                    Module[] arrModule = cr.CompiledAssembly.GetModules();

                    foreach (Module mod in arrModule)

                    {

                        Type[] arrType = mod.GetTypes();

                        foreach (Type t in arrType)

                        {

                            mi = t.GetMethod(MethodName);

                            if (mi != null)

                            {

                                obj = Activator.CreateInstance(t);

                                if (!string.IsNullOrEmpty(UrlUser))

                                {

                                    ((WebClientProtocol)obj).Credentials = new NetworkCredential(UrlUser, UrlUserPwd);

                                }

                                break;

                            }

                        }

                        if (mi != null)

                        {

                            break;

                        }

                    }

                    if (mi == null)

                    {

                        throw new Exception(string.Format("地址[{0}],方法[{1}],不存在。", Url, MethodName));

                    }

                    htObject = new Hashtable();

                    htObject["url"] = Url;

                    htObject["date"] = Date;

                    htObject["obj"] = obj;

                    htObject["mi"] = mi;

                    htObject["methodname"] = MethodName;

                    _lstServer.Add(htObject);

                }

                return mi.Invoke(obj, Args);

            }

            catch (Exception ex)

            {

                if (IsThrowException)

                {

                    throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));

                }

                return null;

            }

        }

    }

    public static class WebServiceHelperSoap

    {

        private static string GetWsClassName(string wsUrl)

        {

            string[] parts = wsUrl.Split('/');

            string[] pps = parts[parts.Length - 1].Split('.');

            return pps[0];

        }

        public static object InvokeWebService(string url, string nameSpace, string classname, string methodname, object[] args)

        {

            if ((classname == null) || (classname == ""))

            {

                classname = WebServiceHelperSoap.GetWsClassName(url);

            }

            try

            {                   //获取WSDL  

                WebClient wc = new WebClient();

                Stream stream = wc.OpenRead(url + "?WSDL");

                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);

                CSharpCodeProvider icc = new CSharpCodeProvider();

                //设定编译参数                 

                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 (System.CodeDom.Compiler.CompilerError ce in cr.Errors)

                    {

                        sb.Append(ce.ToString());

                        sb.Append(System.Environment.NewLine);

                    }

                    throw new Exception(sb.ToString());

                }

                //生成代理实例,并调用方法  

                System.Reflection.Assembly assembly = cr.CompiledAssembly;

                Type t = assembly.GetType(nameSpace + "." + classname, true, true);

                SoapHeader soapHeader = new SoapHeader("SecurityHeader");

                soapHeader.AddProperty("SecurityKey", "850");

                FieldInfo[] arry = t.GetFields();

                FieldInfo client = null;

                object clientkey = null;

                if (soapHeader != null)

                {

                    client = t.GetField(soapHeader.ClassName + "Value");

                    Type typeClient = assembly.GetType(nameSpace + "." + soapHeader.ClassName);

                    clientkey = Activator.CreateInstance(typeClient);

                    foreach (KeyValuePair<string, object> property in soapHeader.Properties)

                    {

                        typeClient.GetField(property.Key).SetValue(clientkey, property.Value);

                    }

                }

                object obj = Activator.CreateInstance(t);

                //设置Soap 

                if (soapHeader != null)

                {

                    client.SetValue(obj, clientkey);

                }

                System.Reflection.MethodInfo mi = t.GetMethod(methodname);

                return mi.Invoke(obj, args);

                // PropertyInfo propertyInfo = type.GetProperty(propertyname);    

                //return propertyInfo.GetValue(obj, null);

            }

            catch (Exception ex)

            {

                throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));

            }

        }

    }

    public class SecurityHeader : SoapHeader

    {

        public string SecurityKey

        {

            get;

            set;

        }

    }

    public class SoapHeader 

    { 

           

        ///

 

            /// 构造一个SOAP 

            ///

 

            public SoapHeader() 

            { 

                this.Properties = new Dictionary<string, object>(); 

            } 

 

            ///

 

            /// 构造一个SOAP 

            ///

 

            /// SOAP头的类名 

            public SoapHeader(string className) 

            { 

                this.ClassName = className; 

                this.Properties = new Dictionary<string, object>(); 

            } 

 

            ///

 

            /// 构造一个SOAP 

            ///

 

            /// SOAP头的类名 

            /// SOAP头的类属性名及属性值 

            public SoapHeader(string className, Dictionary<string, object> properties) 

            { 

                this.ClassName = className; 

                this.Properties = properties; 

            } 

 

            ///

 

            /// SOAP头的类名 

            ///

 

            public string ClassName { get; set; } 

 

            ///

 

            /// SOAP头的类属性名及属性值 

            ///

 

            public Dictionary<string, object> Properties { get; set; } 

 

            ///

 

            /// SOAP头增加一个属性及值 

            ///

 

            /// SOAP头的类属性名 

            /// SOAP头的类属性值 

            public void AddProperty(string name, object value) 

            { 

                if (this.Properties == null

                { 

                    this.Properties = new Dictionary<string, object>(); 

                } 

                Properties.Add(name, value); 

            } 

        } 

  

客户端使用测试代码:

    [TestClass]

    public class UnitTest1

    {

        ///

        /// 加密秘钥

        ///

        private static string KEY = "whePmcRG";

        ///

        /// 加密向量

        ///

        private static byte[] IV = { 0x12, 0x23, 0x34, 0x45, 0x56, 0xAB, 0xCD, 0xEF };

        private string url = "http://localhost:28005/WebService1.asmx"//"http://192.168.6.115/WEBSERVERtest/WebService1.asmx"(IIS服务里站点);

        //需手动 添加服务 WebApplication1

        [TestMethod]

        public void TestMethod1()

        {

            AddInt(5,6);

            HelloWorld1("你好欢迎光临!");

            SelectBaseInfo("0");

        }

        public string AddInt(int A,int B)

        {

            //string url = "http://localhost:28005/WebService1.asmx";  //"http://192.168.6.115/WEBSERVERtest/WebService1.asmx"(IIS服务里站点);

            object retValue = null;

            var vir = "";                           //安装虚拟目录

            List<object> list = new List<object>(); //WebService参数

            string MethodName = "";                 //WebService方法

            try

            {

                vir = Encrypt(url);

                MethodName = "AddInt";

                //list.Add(string.Format("A:{0}|B:{1}|vir:{3}|htoken:{4}",

                //        A,

                //        B,

                //        vir,

                //        Encrypt("")));

                list.Add(A);

                list.Add(B);

                retValue = WebServiceHelper2.InvokeWebService(url, MethodName, list.ToArray(), "", true);

            }

            catch (Exception e)

            {

                throw new Exception("网络连接失败,请稍后再试.");

            }

            if (retValue == null) throw new Exception("调用接口失败,请稍后再试");

            string jsonStr = retValue.ToString();

            //Carpa.Web.Ajax.JavaScriptSerializer ser = Carpa.Web.Ajax.JavaScriptSerializer.CreateInstance();

            //IHashObject validateInfo = ser.Deserialize(jsonStr);

            //int retCode = validateInfo.GetValue("code", -1);

            //if (retCode > 0)

            //{

            //    Delete(dogNum, connectionStr);

            //}

            return jsonStr;

           

        }

        public string HelloWorld1(string s)

        {

            //string url = "http://localhost:28005/WebService1.asmx";  //"http://192.168.6.115/WEBSERVERtest/WebService1.asmx"(IIS服务里站点);

            object retValue = null;

            var vir = "";                           //安装虚拟目录

            List<object> list = new List<object>(); //WebService参数

            string MethodName = "";                 //WebService方法

            try

            {

                vir = Encrypt(url);

                MethodName = "HelloWorld1";

                //list.Add(string.Format("A:{0}|B:{1}|vir:{3}|htoken:{4}",

                //        A,

                //        B,

                //        vir,

                //        Encrypt("")));

                list.Add(s);

                retValue = WebServiceHelper2.InvokeWebService(url, MethodName, list.ToArray(), "", true);

            }

            catch (Exception e)

            {

                throw new Exception("网络连接失败,请稍后再试.");

            }

            if (retValue == null) throw new Exception("调用接口失败,请稍后再试");

            string jsonStr = retValue.ToString();

            //Carpa.Web.Ajax.JavaScriptSerializer ser = Carpa.Web.Ajax.JavaScriptSerializer.CreateInstance();

            //IHashObject validateInfo = ser.Deserialize(jsonStr);

            //int retCode = validateInfo.GetValue("code", -1);

            //if (retCode > 0)

            //{

            //    Delete(dogNum, connectionStr);

            //}

            return jsonStr;

        }

        public string SelectBaseInfo(string s)

        {

            //string url = "http://localhost:28005/WebService1.asmx";  //"http://192.168.6.115/WEBSERVERtest/WebService1.asmx"(IIS服务里站点);

            object retValue = null;

            var vir = "";                           //安装虚拟目录

            List<object> list = new List<object>(); //WebService参数

            string MethodName = "";                 //WebService方法

            try

            {

                vir = Encrypt(url);

                MethodName = "SelectBaseInfo";

                //list.Add(string.Format("A:{0}|B:{1}|vir:{3}|htoken:{4}",

                //        A,

                //        B,

                //        vir,

                //        Encrypt("")));

                list.Add(s);

                retValue = WebServiceHelper2.InvokeWebService(url, MethodName, list.ToArray(), "", true);

            }

            catch (Exception e)

            {

                throw new Exception("网络连接失败,请稍后再试.");

            }

            if (retValue == null) throw new Exception("调用接口失败,请稍后再试");

            string jsonStr = retValue.ToString();

            return jsonStr;

        }

        ///

        /// 字符串加密

        ///

        /// 明文字符串

        /// 加密钥匙

        /// 加密向量

        ///

        public static string Encrypt(string encryptString)

        {

            try

            {

                byte[] rgbKey = Encoding.UTF8.GetBytes(KEY);

                byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);

                DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();

                MemoryStream mStream = new MemoryStream();

                CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, IV), CryptoStreamMode.Write);

                cStream.Write(inputByteArray, 0, inputByteArray.Length);

                cStream.FlushFinalBlock();

                return Convert.ToBase64String(mStream.ToArray());

            }

            catch

            {

                return encryptString;

            }

        }

        ///

        /// 字符串解密

        ///

        /// 待解密字符串

        ///

        public static string Decrypt(string decryptString)

        {

            if (string.IsNullOrEmpty(decryptString)) return "";

            byte[] rgbKey = Encoding.UTF8.GetBytes(KEY);

            //byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(sIv);

            byte[] byEnc;

            try

            {

                byEnc = Convert.FromBase64String(decryptString);

            }

            catch

            {

                return null;

            }

            DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();

            MemoryStream ms = new MemoryStream(byEnc);

            CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(rgbKey, IV), CryptoStreamMode.Read);

            StreamReader sr = new StreamReader(cst);

            return sr.ReadToEnd();

        }

    }

你可能感兴趣的:(asp.net,服务器,c#)