Sunday, October 13, 2013

URL Routing in ASP.Net Web Forms - Same number of Parameters

Yesterday, our team faced an interesting issue in URL Routing. My subordinate was finding difficulty in resolving a problem with routes having same number of parameters. So, I thought of sharing it with you the same. Issue goes like this.

ISSUE

Two routes were created in Global.asax file as shown below:

routeCollection.MapPageRoute("ProjectType", "{dealtype}/{searchstring}", "~/result.aspx");
routeCollection.MapPageRoute("CompanyDetail", "company-details/{personID}", "~/companyregistration.aspx");

Now, in the above case, in "ProjectType" route both the parameters are dynamic whereas for the "CompanyDetail" route, one part of the route is hard-coded i.e. 'company-details' and other parameter is dynamically set. But, when I redirect to route of company details, it was still requesting result.aspx instead of companyregistration.aspx. We tried both the ways of redirecting to the route.

Response.RedirectToRoute("CompanyDetail", new { personID = lngPersonID.ToString() });

OR

Response.Redirect("company-details/" + lngPersonID.ToString());

But it was requesting result.aspx.

RESOLUTION

After trying quite a few options, we made the following change in the Global.asax file and it worked. We just changed the order of the route declaration.

routeCollection.MapPageRoute("CompanyDetail", "company-details/{personID}", "~/companyregistration.aspx");
routeCollection.MapPageRoute("ProjectType", "{dealtype}/{searchstring}", "~/result.aspx");

After changing the order of declaration, both the routes were working.

CONCLUSION

After looking at this issue, following points can be concluded:

Routes without any hard-coded identifier must be declared at the last.
If there are more than one routes without any hard-coded identifier and having the same number of identifier, then the route declared first will override all others and will be considered by ASP.Net.

I hope this article was useful to you. You can post your inputs and extra information in the comments section.

You can also subscribe to this blog by registering your email to get notifications of new posts.

Thanks & Regards,
Munjal

1 comment:

  1. Hi, I have got the same issue but I cannot solve it as you said, is there another way to accomplish that, thank you. here is the issue if you could have a quick look http://stackoverflow.com/questions/21206665/redirect-loop-error-asp-net-4-0-webforms-routing

    ReplyDelete