当前位置: 移动技术网 > IT编程>开发语言>.net > Asp.Net HttpHandler 妙用

Asp.Net HttpHandler 妙用

2017年12月12日  | 移动技术网IT编程  | 我要评论
如:输出xmldom,注销并跳转,并没有什么html的输出,很是麻烦,需要新建一个页,删除多余的html,并在page_load里面写处理代码。而使用httphandler
如:输出xmldom,注销并跳转,并没有什么html的输出,很是麻烦,需要新建一个页,删除多余的html,并在page_load里面写处理代码。而使用httphandler就不需要这么麻烦了。
可以用任何符合公共语言规范 (cls) 的语言编写自定义 http 处理程序来处理特定的、预定义类型的 http 请求。响应这些特定请求的是在 httphandler 类中定义的可执行代码,而不是常规的 asp 或 asp.net web 页。http 处理程序向您提供一种方法,使您可以与 iis web 服务器的低级别的请求和响应服务交互,同时提供极其类似于 isapi 扩展但编程模型较为简单的功能。
例如我现在需要实现一个注销并跳转的logout.aspx页面,下面的示例主要实现了响应客户端对名为 logout.aspx 的页的请求,实现注销并跳转。对 logout.aspx 的所有请求均由包含在程序集 webuc.dll 中的命名空间 webuc.httphandler 中的 logouthttphandler 提供服务。
修改web.config,在<system.web></system.web>中增加如下脚本:
<httphandlers>
<add verb="get" path="logout.aspx" type="webuc.httphandler.logouthttphandler, webuc" />
</httphandlers>
其中webuc.httphandler.logouthttphandler是我要实现logout.aspx功能的类,webuc是我web项目的dll。(具体介绍可以参阅msdn)
下面是logouthttphandler的代码,继承借口,重写方法和属性。 
复制代码 代码如下:

using system;
using system.web;
using system.web.caching;
using system.web.security;
namespace webuc.httphandler
{
public class logouthttphandler : ihttphandler
{
/// <summary>
/// 通过实现 ihttphandler 接口的自定义 httphandler 启用 http web 请求的处理。
/// </summary>
/// <param name="context">httpcontext 对象,它提供对用于为 http 请求提供服务的内部服务器对象(如 request、response、session 和 server)的引用。 </param>
public void processrequest (httpcontext context)
{
formsauthentication.signout();
context.response.redirect("login.aspx",true);
}
/// <summary>
/// 获取一个值,该值指示其他请求是否可以使用 ihttphandler 实例。
/// </summary>
public bool isreusable
{
get
{
return false;
}
}
}
}
}

编译后,我就可以直接使用http://***/logout.aspx 来实现注销了,而实际上,我的web目录下并没有logout.aspx这个文件,同样,这个技巧可以用在很多方面,例如防止盗链,下载统计等。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网