纯ASP.NET路由到类不是aspx页面

use*_*291 0 asp.net asp.net-mvc asp.net-mvc-3

我需要在现有的asp.net应用程序中进行路由 - 而不是asp.net mvc(是的,我知道我应该转换但是现在说它不可能,所以不要告诉我:)) - 我该怎么做路由到一个普通的类而不是一个aspx页面,因为我看到的所有示例代码总是与aspx页面一样:

http://msdn.microsoft.com/en-us/magazine/dd347546.aspx

确切地说,我想在MVC控制器路由中做一些事情:例如产品的控制器是您通过http://domain.com/product访问的纯类

Mic*_*out 5

ASP.NET MVC和ASP.NET Web Forms共享相同的路由基础结构,因为两个框架最终都需要提供一个IHttpHandler来处理HTTP请求:

IHttpHandler接口从一开始就是ASP.NET的一部分,Web Form(System.Web.UI.Page)是IHttpHandler.

(来自问题中链接的MSDN文章)

在ASP.NET MVC中,使用System.Web.Mvc.MvcHandler该类,然后将该代理委托给控制器以进一步处理请求.在ASP.NET Web窗体中,通常使用System.Web.UI.Page表示.aspx文件的类,但也可以使用与.ashx文件关联的 IHttpHandler文本.

因此,您可以路由到.ashx处理程序,作为.aspx Web窗体页面的替代方法.两者都实现IHttpHandler(如同MvcHandler),但前者就是它所做的一切.这就像你可以得到处理(路由)请求的"纯类"一样接近.由于处理程序部分只是一个接口,因此您可以自由地继承自己的类.

<%@ WebHandler Language="C#" Class="LightweightHandler" %>

using System.Web;

public class LightweightHandler : YourBaseClass, IHttpHandler
{
  public void ProcessRequest(HttpContext context)
  {
    context.Response.ContentType = "text/plain";
    context.Response.Write("Hello world!");
  }

  public bool IsReusable { get { return false; } }
}
Run Code Online (Sandbox Code Playgroud)

请注意,IRouteHandler只需返回以下实例IHttpHandler:

public IHttpHandler GetHttpHandler(RequestContext requestContext);
Run Code Online (Sandbox Code Playgroud)

如果使用.ashx文件,您可能需要跳过一些箍来使用BuildManager*来实例化您的处理程序.如果没有,您可以新建一个类的实例并将其返回:

public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
  // In case of an .ashx file, otherwise just new up an instance of a class here
  IHttpHandler handler = 
    BuildManager.CreateInstanceFromVirtualPath(path, typeof(IHttpHandler)) as IHttpHandler;

  // Cast to your base class in order to make it work for you
  YourBaseClass instance = handler as YourBaseClass;
  instance.Setting = 42;
  instance.DoWork();

  // But return it as an IHttpHandler still, as it needs to do ProcessRequest
  return handler;
}
Run Code Online (Sandbox Code Playgroud)

请参阅此问题的答案,以便更深入地分析路由纯IHttpHandler:ASP.NET Routing可用于为.ashx(IHttpHander)处理程序创建"干净"的URL吗?

**我不完全确定BuildManager示例,如果我的部分出错,请有人纠正我*