ASP.NET MVC和ASP .NET Web窗体共享相同的路由基础设施中,这两个框架最终需要拿出一个IHttpHandler
来处理HTTP请求:
IHttpHandler接口一直以来, 开始ASP.NET的一部分,一个Web窗体(一个System.Web.UI.Page)是一个IHttpHandler。
(从问题链接MSDN文章)
在ASP.NET MVC的System.Web.Mvc.MvcHandler
类用于,which then delegates to a controller该请求的进一步处理。在ASP.NET Web窗体中,通常使用表示.aspx文件的System.Web.UI.Page
类,但也可以使用与.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; } }
}
注意的IRouteHandler
只需要返回的IHttpHandler
一个实例:
public IHttpHandler GetHttpHandler(RequestContext requestContext);
您可能需要通过一些跳铁圈使用实例化处理程序的BuildManager如果使用.ashx的文件*。如果没有,你可以只新你的类的实例并返回它:
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;
}
看到这个问题的答案路由纯IHttpHandlers的更深入的分析:Can ASP.NET Routing be used to create “clean” URLs for .ashx (IHttpHander) handlers?
**我'不完全确定BuildManager的例子,有人请纠正我,如果我得到那部分错误*
要上课吗?就像在App_Code/YourClass.cs中一样? – justinlabenne 2012-01-07 21:39:31
不,我想在MVC控制器路由中这样做:例如产品的控制器是一个纯粹的类,您可以通过http://domain.com/product – user310291 2012-01-07 22:17:33
访问什么是纯类?控制器从System.Web.Mvc.Controller继承,而Web Form从System.Web.UI.Page继承。两者都是类,什么使得第一个纯粹的和第二个不是? – 2012-01-08 00:08:42