2011-07-27 123 views
1

我正在ASP.net 4.0中使用路由站點,它不在MVC體系結構中。 這裏我遇到了一個很大的問題,即我無法通過路由調用任何處理程序文件。如何在asp.net 4.0中調用* .ashx處理程序路由

我寫這篇文章的代碼在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

它是catpcha頁?似乎你的路線正在接受這個請求,並沒有返回正確的值 –

回答

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)); 
    } 

} 
相關問題