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