1.一般调用ashx,使用switch
public void ProcessRequest(HttpContext context)
{
switch (context.Request["action"])
{
case "Getxxx":
break;
case "Setxxx":
break;
....
}
}
jquery调用
$.post('xxx.ashx?action=Getxxx', { }, function (data) {});
如果方法很多switch将变得很大,不易维护
2.使用反射调整
public class Pub : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
try
{
if (context.Request.Form[0] == null)
{
context.Response.Write("Error");
return;
}
string FunctionName = context.Request.Form[0];
object[] parameters = null;
if (context.Request.Form.Count - 1 > 0)
{
parameters = new object[context.Request.Form.Count - 1];
for (int i = 0; i < parameters.Length; i++)
{
parameters[i] = context.Request.Form[i + 1];
}
}
MethodInfo method = typeof(Pub).GetMethod(FunctionName);
object Result = "Error";
if (method != null)
{
Result = method.Invoke(this, parameters);
}
context.Response.Write(Result);
}
catch
{
context.Response.Write("Error");
}
}
public string Getxxx(string t)
{
return "xxxx";
}
}
使用jquery调用
$.post('Pub.ashx', { "fun": "Getxxx", "t": "" }, function (data) { });
jquery调用的参数第一位必须是函数名"Getxxx",后面跟着请求参数
3.可以进一步改进ashx,做一个基类,放一些公共的方法,或者做一些公共的处理
public class ControllerBase : IHttpHandler
{
private HttpContext _myContext = null;
private System.Type _type = null;
public System.Type Type
{
get { return _type; }
set { _type = value; }
}
public HttpContext MyContext
{
get { return _myContext; }
set { _myContext = value; }
}
public ControllerBase() { }
public ControllerBase(HttpContext context)
{
this._myContext = context;
}
public void ProcessRequest(HttpContext context)
{
this._myContext = context;
try
{
if (context.Request.Form[0] == null)
{
context.Response.Write("Error");
return;
}
object[] parameters = null;
Type[] types = new Type[] { };
if (context.Request.Form.Count - 1 > 0)
{
parameters = new object[context.Request.Form.Count - 1];
types = new Type[context.Request.Form.Count - 1];
for (int i = 0; i < parameters.Length; i++)
{
parameters[i] = context.Request.Form[i + 1];
types[i] = typeof(string);
}
}
MethodInfo method = this.Type.GetMethod(context.Request.Form[0], types);
object Result = "Error";
if (method != null)
{
Result = method.Invoke(this, parameters);
}
context.Response.Write(Result);
}
catch
{
context.Response.Write("Error");
}
}
}
其它子类继承基类
public class Mod : ControllerBase
{
public Mod()
{
base.Type = typeof(Mod);
}
public string Getxxx()
{
return "xxx";
}
}