RouteData.Values are accessible in Web Forms pages. To access and use RouteData or RouteData.Values in Ajax Handler like .ashx inherit the class System.Web.UI.Page
before the interface IHttpHandler
.
Ajax call for RouteData
For example you make an ajax call through following URL in your project
http://localhost:9021/ajax/smart-phones
Routing in Global.asax
Following route is defined in Global.asax
void RegisterRoutes(System.Web.Routing.RouteCollection routes)
{
routes.MapPageRoute("handle", "ajax/{cat}", "~/Handler.ashx");
}
void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(System.Web.Routing.RouteTable.Routes);
}
Generic Handler for Ajax calls
The Generic Handler will be like this.
<%@ WebHandler Language="C#" Class="HandleAjax" %>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
public class Handler : System.Web.UI.Page, IHttpHandler
{
public bool IsReusable {
get {
return false;
}
}
public void ProcessRequest(HttpContext context)
{
string category = context.Request.RequestContext.RouteData.Values["cat"] as string
//Rest of Your Code Here
}
}
In the above code snippet, in the line public class Handler : System.Web.UI.Page, IHttpHandler
, inheriting System.Web.UI.Page
is additional.
Drawback: Heavy Generic Hanlder
Inheriting System.Web.UI.Page
in generic handler will make the handler heavy as it make inherit the objects as ASP.Net web page do in web forms but not as heavier as a normal ASP.Net web page because this will not follow the Web Page life cycle as of usual Web Forms page do.
Posted Status in Programming