在好例子网,分享、交流、成长!
您当前所在位置:首页C# 开发实例C#语言基础 → webAPI 反射dll(仅一个类文件,供参考学习)

webAPI 反射dll(仅一个类文件,供参考学习)

C#语言基础

下载此实例
  • 开发语言:C#
  • 实例大小:2.69KB
  • 下载次数:47
  • 浏览次数:489
  • 发布时间:2016-06-13
  • 实例类别:C#语言基础
  • 发 布 人:az6161311
  • 文件格式:.rar
  • 所需积分:0
 相关标签: 反射 API web dLL webapi

实例介绍

【实例简介】webapi动态加载执行dll访问

【实例截图】

无截图

【核心代码】


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Web.Http;
using System.Configuration;
using System.Web;
namespace MaxiTai.Demo.WebAPI
{
    public class RequestController : ApiController
    {
         

        /// <summary>
        ///  获取当前应用的路径下所有dll包含的命名空间
        /// </summary>
        /// <param name="dllNames">指定的dll,多个按照|隔开</param>
        /// <returns></returns>
 

        [HttpPost]
        public object GetApi(InputModel input)
        {
            //var methName = "GetModel";
            //var className = "Test";
            //var namespaceName = "MaxiTai.Demo.BLL";
            //object[] parameters = new object[] { "{'id':'1','name':'张三','age':18,'sex':'男'}" };
            var methName = input.methName;
            var className = input.className;
            var namespaceName = input.namespaceName;
            object[] parameters = input.parameters == null ? new object[] { } : input.parameters;
            object result = null;
            try
            {
                object[] Iparameters = null;
                if (parameters != null && parameters.Length > 0 && parameters[0] != null)
                {
                    Iparameters = new object[parameters.Length];
                }
                var namespaceNameAssembly = Assembly.Load(namespaceName);
                if (namespaceNameAssembly != null)
                {
                    var classes = namespaceNameAssembly.GetType(namespaceName   "."   className);
                    if (classes != null)
                    {
                        object reflectTest = Activator.CreateInstance(classes);
                        var Methods = classes.GetMethods();
                        var Method_list = Methods.Where(w => w.Name == methName).ToList();
                        //Type[] TypeList = new Type[parameters.Length];
                        MethodInfo Method = null;
                        //for (int i = 0; i < parameters.Length; i  )
                        //{
                        //    TypeList[i] = parameters[i].GetType();
                        //}
                        //MethodInfo Method = classes.GetMethod(methName, TypeList); ;
                        if (Method_list.Count() == 1)
                        {
                            Method = Method_list.FirstOrDefault(w => w.Name == methName);
                        }
                        else if (Method_list.Count() > 1)
                        {
                            var SelectMethod = 0;
                            var MethodIndex = 0;
                            List<MethodInfo> SelectMethodList = new List<MethodInfo>();
                            for (int i = 0; i < Method_list.Count(); i  )
                            {
                                if (parameters.Length == Method_list[i].GetParameters().Count())
                                {
                                    SelectMethodList.Add(Method_list[i]);
                                    MethodIndex = i;
                                    SelectMethod  ;
                                }
                            }
                            if (SelectMethod == 1)
                            {
                                Method = Method_list[MethodIndex];
                            }
                            else
                            {
                                for (int i = 0; i < SelectMethodList.Count; i  )
                                {
                                    var parCount = 0;
                                    var pis = SelectMethodList[i].GetParameters();
                                    for (int j = 0; j < pis.Count(); j  )
                                    {

                                        if (pis[j].ParameterType.Name == parameters[j].GetType().Name)
                                        {
                                            parCount  ;
                                        }
                                    }
                                    if (parCount == pis.Count())
                                    {
                                        Method = SelectMethodList[i];
                                        break;
                                    }
                                    //var prType= typeof();
                                    //piList[i].ParameterType.Name ;
                                }
                            }
                        }
                        if (Method != null)
                        {
                            var parametersType = Method.GetParameters();

                            for (int i = 0; i < parametersType.Length; i  )
                            {
                                if (parametersType[i].ParameterType.Namespace != "System") //不为系统参数
                                {
                                    var requestModel = ConvertObject(parameters[i], parametersType[i].ParameterType);
                                    System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer();
                                    if (parameters[i] != null)
                                    {
                                        var deser = jss.Deserialize<Dictionary<string, object>>(parameters[i].ToString());
                                        var resultProperties = requestModel.GetType().GetProperties();


                                        foreach (var item in resultProperties)
                                        {
                                            foreach (var deserItem in deser.Keys)
                                            {
                                                if (item.Name == deserItem)
                                                {
                                                    object deserValue = "";
                                                    deser.TryGetValue(deserItem, out deserValue);
                                                    item.SetValue(requestModel, ConvertObject(deserValue, item.PropertyType));
                                                }
                                            }

                                        }
                                        Iparameters[i] = requestModel;
                                    }
                                }
                                else //系统类型参数
                                {
                                    Iparameters[i] = ConvertObject(parameters[i], parametersType[i].ParameterType);
                                }
                            }
                            result = new { result = Method.Invoke(reflectTest, Iparameters) };

                        }
                        else
                        {
                            result = new
                            {
                                error = "方法名不存在",
                                message = @"可能原因:
                                              1.方法名不存在
                                              2.方法被重载,参数不识别"
                            };
                        }

                    }
                    else
                    {
                        result = new
                        {
                            error = "类名不存在"
                        };
                    }
                }

                else
                {
                    result = new
                    {
                        error = "命名空间不存在"
                    };
                }
            }
            catch (Exception ex)
            {

                result = new
                {
                    error = "参数格式不正确",
                    message = ex.Message,
                    errorCode = "方法调用出错"
                };
                // throw new Exception(ex.Message);
            }

            return result;
        }


        #region 将一个对象转换为指定类型
        /// <summary>
        /// 将一个对象转换为指定类型
        /// </summary>
        /// <param name="obj">待转换的对象</param>
        /// <param name="type">目标类型</param>
        /// <returns>转换后的对象</returns>
        private object ConvertObject(object obj, Type type)
        {
            if (type == null) return obj;
            if (obj == null) return type.IsValueType ? Activator.CreateInstance(type) : null;

            Type underlyingType = Nullable.GetUnderlyingType(type);
            if (type.IsAssignableFrom(obj.GetType())) // 如果待转换对象的类型与目标类型兼容,则无需转换
            {
                return obj;
            }
            else if ((underlyingType ?? type).IsEnum) // 如果待转换的对象的基类型为枚举
            {
                if (underlyingType != null && string.IsNullOrEmpty(obj.ToString())) // 如果目标类型为可空枚举,并且待转换对象为null 则直接返回  null值
                {
                    return null;
                }
                else
                {
                    return Enum.Parse(underlyingType ?? type, obj.ToString());
                }
            }
            else if (typeof(IConvertible).IsAssignableFrom(underlyingType ?? type)) // 如果目标类型的基类型实现了IConvertible,则直接转换
            {
                try
                {
                    return Convert.ChangeType(obj, underlyingType ?? type, null);
                }
                catch
                {
                    return underlyingType == null ? Activator.CreateInstance(type) : null;
                }
            }
            else
            {
                TypeConverter converter = TypeDescriptor.GetConverter(type);
                if (converter.CanConvertFrom(obj.GetType()))
                {
                    return converter.ConvertFrom(obj);
                }
                ConstructorInfo constructor = type.GetConstructor(Type.EmptyTypes);
                if (constructor != null)
                {
                    object o = constructor.Invoke(null);
                    PropertyInfo[] propertys = type.GetProperties();
                    Type oldType = obj.GetType();
                    foreach (PropertyInfo property in propertys)
                    {
                        PropertyInfo p = oldType.GetProperty(property.Name);
                        if (property.CanWrite && p != null && p.CanRead)
                        {
                            property.SetValue(o, ConvertObject(p.GetValue(obj, null), property.PropertyType), null);
                        }
                    }
                    return o;
                }
            }
            return obj;
        }
        #endregion
    }
     
    public class InputModel
    {
        public string namespaceName { get; set; }
        public string className { get; set; }
        public string methName { get; set; }
        public object[] parameters { get; set; }
    }
    public class FrameworkModels
    {
        public FrameworkModels()
        {
            className = new List<className>();
        }

        public string namespaceName { get; set; }
        public List<className> className { get; set; }
    }


    public class className
    {
        public className()
        {
            methName = new List<string>();
        }
        public string Name { get; set; }
        public List<string> methName { get; set; }
    }
}


标签: 反射 API web dLL webapi

实例下载地址

webAPI 反射dll(仅一个类文件,供参考学习)

不能下载?内容有错? 点击这里报错 + 投诉 + 提问

好例子网口号:伸出你的我的手 — 分享

网友评论

发表评论

(您的评论需要经过审核才能显示)

查看所有0条评论>>

小贴士

感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。

  • 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
  • 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
  • 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
  • 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。

关于好例子网

本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明

;
报警