ASP.NET IHttpHandler实现扩展性的方法调用(转)

有时需要在HttpHandler里按需调用方法和参数,一般会硬编码书写多个switch(Request["method"])的case,并在case里获取响应参数并类型转换以调用方法,以下方法封装该需求,实现简单的方法调用。

by peter 2009.8.9

==================================

using System;
using System.Web;
using System.Reflection;

namespace Latermoon.Web
{
/// <summary>
/// 根据请求中的method自动调用相应方法处理
/// </summary>
public abstract class MultiMethodHttpHandler : IHttpHandler
{
/// <summary>
/// 使 ASP.NET 能够读取客户端在 Web 请求期间发送的 HTTP 值
/// </summary>
public HttpRequest Request;
/// <summary>
/// 封装来自 ASP.NET 操作的 HTTP 响应信息
/// </summary>
public HttpResponse Response;
/// <summary>
/// 提供用于处理 Web 请求的 Helper 方法
/// </summary>
public HttpServerUtility Server;

/// <summary>
/// 默认的请求入口
/// </summary>
/// <param name=”context”></param>
public virtual void ProcessRequest(HttpContext context)
{
//初始化
Request = context.Request;
Response = context.Response;
Server = context.Server;
try
{
//获取方法名
string methodName = Request["method"];

if (string.IsNullOrEmpty(methodName))
{
throw new TargetException(“Method not found”);
}

//获取方法
MethodInfo method = this.GetType().GetMethod(methodName);
if (method == null)
{
throw new TargetException(“Method ” + methodName + ” not found”);
}
else
{
//获取参数信息
ParameterInfo[] parameters = method.GetParameters();
if (parameters.Length == 0)
{
//调用无参数方法
method.Invoke(this, null);
}
else
{
//填充参数
object[] values = new object[parameters.Length];
for (int i = 0; i < parameters.Length; i++)
{
//自动类型转换
values[i] = Convert.ChangeType(Request[parameters[i].Name], parameters[i].ParameterType);
}
//调用有参数方法
method.Invoke(this, values);
}
}
}
catch (Exception ex)
{
InvokeError(ex);
}
}

/// <summary>
/// 调用出现异常时触发
/// </summary>
public abstract void InvokeError(Exception ex);

public virtual bool IsReusable
{
get { return false; }
}

}
}

==================================

有了MultiMethodHttpHandler,让新的HttpHandler继承它。

public class ManagerHandler : MultiMethodHttpHandler
{
public void DisplayName()
{
Response.ContentType = “text/html”;
Response.Write(“My name is Peter.”);
}

public void Display(string name, int age)
{
Response.ContentType = “text/html”;
Response.Write(“My name is “);
Response.Write(name);
Response.Write(“, age “);
Response.Write(age);
}

/// <summary>
/// 调用出错
/// </summary>
/// <param name=”ex”></param>
public override void InvokeError(Exception ex)
{
Response.ContentType = “text/html”;
Response.Write(ex.Message);
}
}

==================================

访问接口:

http://xxx.com/ManagerHandler.ashx?method=DisplayName

http://xxx.com/ManagerHandler.ashx?method=Display&name=peter&age=2

这样可以在一个HttpHandler里放置多种相关方法,而不需硬编码写switch(Request["method"])。

 

转自:http://blog.latermoon.com/?m=200908 
 

posted @ 2012-06-15 10:23  acles  阅读(242)  评论(0)    收藏  举报