65.9K
CodeProject 正在变化。 阅读更多。
Home

Httphandlers ASP.NET 2.0

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.39/5 (13投票s)

2007年6月27日

CPOL

2分钟阅读

viewsIcon

91654

downloadIcon

3676

本教程描述了 ASP.NET 2.0 中一个简单的 Httphandlers。

引言

大多数网站都是动态的,它们的网址很难记住。对于普通用户来说,很难记住像 http://www.himachalsoft.com/userhome.aspx?catid=2&userid=34 这样的网址。然而,像 http://www.himachalsoft.com/prashant.aspx 这样的网址就很容易记住。.NET 为我们提供了创建用户友好型(易于记忆)网址的功能。此外,如果有人在谷歌或任何其他搜索引擎上搜索 prashant,那么到达上述网址的机会就会更容易。让我们看看如何操作。

背景

在 .NET 之前,创建友好网址的唯一方法是使用通常在 C++ 中开发的 ISAPI 扩展。 ISAPI 充当您的 Web 服务器和客户端之间的过滤器。每次客户端向服务器发出请求时,它都会通过该过滤器。创建 ISAPI 过滤器意味着需要了解 c++ 或所需的语言。此外,用户将网站托管在第三方 Web 服务器上,您不能在其中安装您的组件(尽管一些 Web 托管公司允许这样做),或者您必须拥有专用 Web 服务器。在 .NET 中,您可以完全支持 ISAPI 所做的事情,并且您还可以在不为 httphandlers 配置 Web 服务器的情况下完成许多任务。

使用代码

让我们假设您的网站中有一个 users 文件夹。此文件夹中有一个页面 default.aspx。您的网站允许用户注册。每个注册用户都会获得一个网址,他可以与他的朋友、博客等分享。例如 http://www.himachalsoft.com/prashant.aspx。实际上,没有 prashant.aspx 文件。为了实现这种“魔力”,让我们首先创建一个 httphandler 来完成这项工作。创建一个新的类项目。类 UrlHandler 实现 IhttpHandler 接口并实现两种方法。 IsReusable() 和 ProcessRequest()。 process request 中的代码检查当前请求是否包含文件夹名称“Users”,然后检索文件夹名称后的字符串并删除 .aspx 扩展名以获取用户名。然后它会显示用户名。在实际场景中,可以在数据库中查找用户名,验证并加载用户特定数据。

创建一个新的网站。添加上面创建的 handler dll 的引用。在其中添加一个“Users”文件夹。将条目添加到您的 webconfig,如下所示。现在,如果您尝试打开一个页面,例如 http://www.himachalsoft.com/users/prashant.aspx,您将收到 welcome prashant 作为输出。但是,实际上这样的页面不存在。您可以以此示例为基础,从数据库验证用户名(或产品名称)。

using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
namespace MyHandler
{
    class UrlHandler : IHttpHandler
    {
        #region IHttpHandler Members
        public bool IsReusable
        {
            get { return false; }
        }
        public void ProcessRequest(HttpContext context)
        {
            string vPath = context.Request.RawUrl;
        //The hard coded value for path can be put in config file to create rules
        int vIndexOfFolder = vPath.IndexOf("/users/", StringComparison.OrdinalIgnoreCase);
            if (vIndexOfFolder > 0)
            {
            string vUserName = vPath.Substring(vIndexOfFolder + 7);
            //remove .aspx extension
            vUserName = vUserName.Substring(0,vUserName.Length - 5);
            context.Response.Write("Welcome " & vUserName);
            }
        }
        #endregion
    }
}

//Webconfig
 <httpHandlers >
   <add verb="*" path="users/*.aspx" type="MyHandler.UrlHandler,MyHandler" />
  </httpHandlers>
© . All rights reserved.