Gaurav Agrawal
Gaurav Agrawal

Reputation: 4431

How to call *.ashx handler in asp.net 4.0 Routing

I am working in ASP.net 4.0 with Routing site and it is not in MVC Architecture. Here i got a big problem i.e. i can't call any handler file through routing.

I write this code in global.asax page

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

and in CustomRouteHandler class

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

While i am calling any handler file in this site it throws an error i.e.

Type 'Captcha' does not inherit from 'System.Web.UI.Page'.

My Question is that how we can call handler files in this site??

What modification wants this route code??

Upvotes: 1

Views: 4006

Answers (1)

user845802
user845802

Reputation:

Use this Code

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

}

Upvotes: 2

Related Questions