我在ASP.net 4.0中使用路由站点,而不是在MVC架构中。 这里我遇到了一个很大的问题,即我无法通过路由调用任何处理程序文件。
我在global.asax页面中编写此代码
public static void RegisterRoutes(System.Web.Routing.RouteCollection routes)
{
routes.Add(new System.Web.Routing.Route("{language}/{*page}", new CustomRouteHandler()));
}
void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(System.Web.Routing.RouteTable.Routes);
}
和CustomRouteHandler类
public class CustomRouteHandler : IRouteHandler
{
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
string language = TemplateControlExtension.GetString(null, requestContext.RouteData.Values["language"]).ToLower();
string page = TemplateControlExtension.GetString(null, requestContext.RouteData.Values["page"]).ToLower();
if (string.IsNullOrEmpty(page))
{
HttpContext.Current.Response.Redirect("/" + language + "/default.aspx");
}
string VirtualPath = "~/" + page;
if (language != null)
{
TemplateControlExtension.Language = language;
}
return BuildManager.CreateInstanceFromVirtualPath(VirtualPath, typeof(Page)) as IHttpHandler;
}
}
当我在这个站点中调用任何处理程序文件时,它会抛出一个错误,即
Type 'Captcha' does not inherit from 'System.Web.UI.Page'.
我的问题是我们如何在此站点中调用处理程序文件?
什么修改需要此路由代码?
答案 0 :(得分:2)
使用此代码
using System.Web;
using System.Web.Compilation;
using System.Web.Routing;
public class HttpHandlerRouteHandler<T> : IRouteHandler where T : IHttpHandler, new() {
public HttpHandlerRouteHandler() { }
public IHttpHandler GetHttpHandler(RequestContext requestContext) {
return new T();
}
}
public class HttpHandlerRouteHandler : IRouteHandler {
private string _VirtualPath;
public HttpHandlerRouteHandler(string virtualPath) {
this._VirtualPath = virtualPath;
}
public IHttpHandler GetHttpHandler(RequestContext requestContext) {
return (IHttpHandler) BuildManager.CreateInstanceFromVirtualPath(this._VirtualPath, typeof(IHttpHandler));
}
}