views:

30

answers:

1

I need to use routing with parameters in my ASP.NET application.

public class Global : System.Web.HttpApplication
{
    void Application_Start(object sender, EventArgs e)
    {
        RegisterRoutes();
    }

    private void RegisterRoutes()
    {
        var routes = RouteTable.Routes;

        routes.MapPageRoute(
            "Profile",
            String.Format("{0}/{{{1}}}/", "Profile", "Id"),
            "~/Views/Account/Profile.aspx",
            false,
            new RouteValueDictionary {{"Id", null}});
    }
}

Then, by navigating to "/Profile" I want to get on Page_Load method Request.Params["Id"] as null and by navigating to "/Profile/1", Request.Params["Id"] as "1".

Where I made mistake?

+1  A: 

With traditional WebForms I created two Routes in your RegisterRoutes() method.

routes.Add("profile", new Route("profile", 
    new CustomRouteHandler("~/profile.aspx")));
routes.Add("profileId", new Route("profile/{id}", 
    new CustomRouteHandler("~/profile.aspx")));

The CustomRouteHandler looked something like this:

public class CustomRouteHandler : IRouteHandler
{
  public CustomRouteHandler(string virtualPath)    
  {        
      this.VirtualPath = virtualPath;    
  }    
  public string VirtualPath { get; private set; }   

  public IHttpHandler GetHttpHandler(RequestContext requestContext)    
  {        
      string queryString = "";
      HttpRequest request = HttpContext.Current.Request;

      string id = Convert.ToString(requestContext.RouteData.Values["id"]);
      if (id.Length > 0)
      {
          queryString = "?id=" + id;
      }
      HttpContext.Current.RewritePath(          
        string.Concat(          
        VirtualPath,          
        queryString));         
      var page = BuildManager.CreateInstanceFromVirtualPath             
        (VirtualPath, typeof(Page)) as IHttpHandler;        
      return page;    
  }
}
James Lawruk