使用反射 通过ajax调用后台的方法

js代码如下:
$.post(‘http://localhost:58179/Handler1.ashx/say’, ‘{“str”:“111”,“str1”:“啊啊啊”}’, function (data) {

});
这是后台代码:

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;

namespace WebApplication1
{
    /// <summary>
    /// Handler1 的摘要说明
    /// </summary>
    public class Handler1 : IHttpHandler
    {
        string result = string.Empty;
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            var type = Type.GetType("WebApplication1.Class1");
            object obj = Activator.CreateInstance(type, true);

            string mothodName = "say";

            ArrayList list = new ArrayList();
            Dictionary<string, string> jsonDict = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request.Form[0].ToString());
            foreach (var item in jsonDict)
            {
                list.Add(item.Value);
            }
            object[] args = (object[])list.ToArray(typeof(object));//调用方法的参数

            #region 方法一
            //MethodInfo method = type.GetMethod(sayName);
            //if (method != null)
            //{


            //    object obj = Activator.CreateInstance(type, true);
            //    result = (string)method.Invoke(obj, args);
            //}
            #endregion

            #region 方法二
            MethodInfo[] info = type.GetMethods();
            for (int i = 0; i < info.Length; i++)
            {
                var md = info[i];
                //参数集合
                ParameterInfo[] paramInfos = md.GetParameters();
                //paramInfos[0].ParameterType.Name 参数类型
                //方法名相同且参数个数一样
                if (md.Name == mothodName && paramInfos.Length == args.Length)
                {
                    foreach (ParameterInfo parameterInfo in paramInfos)
                    {
                        foreach(object objarg in  args){
                            if (parameterInfo.ParameterType.Name == objarg) { }
                        }
                    }
                    md.Invoke(obj, args);
                }
            }
            #endregion

            context.Response.Write(result);
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值