WCF 动态实现数据契约 ServiceKnownType

来源:互联网 发布:淘宝宝贝改销量 编辑:程序博客网 时间:2024/06/05 13:18


1.在WCF服务添加:

[ServiceKnownType("GetKnownTypes", typeof(KnownTypesProvider))]


2.添加类,  静态方法获取已知类型:


    internal static class KnownTypesProvider    {        public static IEnumerable<Type> GetKnownTypes(ICustomAttributeProvider provider)        {            return GetAssemblyOfType();        }        public static List<Type> GetAssemblyOfType()        {            List<Type> listType = new List<Type>();            string[] files = Directory.GetFiles(AppDomain.CurrentDomain.SetupInformation.ApplicationBase);            foreach (string s in files)            {                string str = s.ToUpper();                if (str.EndsWith(".DLL"))                {                    try                    {                        Assembly ass = Assembly.LoadFrom(str);                        Type[] tps = ass.GetTypes();                        foreach (Type t in tps)                        {                            if (t.BaseType == null)                            {                                continue;                            }                            if (t.BaseType.Name == "数据契约基类")                            {                                listType.Add(t);                            }                        }                    }                    catch (System.Exception ex)                    {                                            }                }            }            return listType;        }    }


0 0