感觉.Net中的httphandler就好像什么来着,我也说不清楚,只是觉得如果利用httphandler来实现一种页面级的权限过滤,或者实现一套自定义的网页后缀方式比较实用。
//这个是一个httphandler的例子,是从.net的Sdk中照搬下来的
using System;
using System.Web;
namespace MyHttpHandler
{
/// <summary>
/// HttpHandlerTest 的摘要说明。
/// </summary>
public class HttpHandlerTest:IHttpHandler
{
public HttpHandlerTest()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
public void ProcessRequest(HttpContext context)
{
//定义request对象
HttpRequest myRequest=context.Request;
//定义response对象
HttpResponse myResponse=context.Response;
myResponse.Write("<html>");
myResponse.Write("<body>");
myResponse.Write("<h1> Hello from Synchronous custom handler. </h1>");
myResponse.Write("</body>");
myResponse.Write("</html>");
}
public bool IsReusable
{
// To enable pooling, return true here.
// This keeps the handler in memory.
get { return true; }
}
}
}
而httphandler工厂,主要是利用了一种反射的机制,对给定条件进行自动的httphandler进行查找
比如说一个Url请求来了,反正先交给工厂,由工厂来决定由哪个处理
using System;
using System.Web;
namespace MyHttpHandler
{
/// <summary>
/// HttpFactoryTest 的摘要说明。
/// </summary>
public class HttpFactoryTest:IHttpHandlerFactory
{
public HttpFactoryTest()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
/// <summary>
/// 实现进行识别url
/// </summary>
/// <param name="context"></param>
/// <param name="requestType"></param>
/// <param name="url"></param>
/// <param name="pathTranslated"></param>
/// <returns></returns>
public virtual IHttpHandler GetHandler(HttpContext context,
String requestType,
String url,
String pathTranslated)
{
string fname=url.Substring(url.LastIndexOf(@"/")+1);
string cname = fname.Substring(0, fname.IndexOf('.'));
string myHandlerName="MyHttpHandler"+"."+cname;
IHttpHandler myHandler;
try
{
//这里就是进行处理的委托了
myHandler=(IHttpHandler)Activator.CreateInstance(Type.GetType(myHandlerName));
}
catch(Exception e)
{
throw new Exception("得到handler失败"+e.Message);
}
return myHandler;
}
public virtual void ReleaseHandler(IHttpHandler handler)
{
}
}
}
在编写httphandler的时候,注册要特别注意,开始我就没有搞懂几个节的意思。
<configuration>
<system.web>
<httpHandlers>
<add verb="*"
path="*.New"
type="MyHandler.New,MyHandler"/>
<add verb="GET,HEAD" //对哪些请求有效
path="*.MyNewFileExtension" //注册成哪种后缀
type="MyHandler.MNFEHandler,MyHandler.dll"/>//1:在程序集中的类名 2:程序集的名称
</httpHandlers>
<system.web>
</configuration>
浙公网安备 33010602011771号