Wednesday, May 4, 2011

ASP.NET URL Routing

I have been hesitant to setup URL Rewriting using IIS. Previously, I setup simple redirects that never seem to work correctly. Plus figuring out the right Regex is a pain.

So I thought I might try again by setting up a single url call to be URL Friendly. I used the IIS URL Rewrite module. I was able to get the URL to accept and process my friendly url but, I had issues with post backs and then the required validators quit working.

So after a little research, I decided to try ASP.NET URL Routing available to for web form in 4.0. It turned out to be pretty easy for what I needed. Here are my steps:

Set up ASP.NET URL Routing in web.config

ASP.NET Development Server:
<httpModules>
<add name="RoutingModule"
type="System.Web.Routing.UrlRoutingModule,
System.Web.Routing,
Version=3.5.0.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35"/>
<!-- ... -->
</httpModules>

IIS 7:
<modules runAllManagedModulesForAllRequests="true">
....
<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</modules>

<handlers>
<add name="UrlRoutingHandler" preCondition="integratedMode" verb="*" path="UrlRouting.axd" type="System.Web.HttpForbiddenHandler, PublicKeyToken=b03f5f7f11d50a3a" />
</handlers>

I wanted the url look like this:
http:/mysite.com/program/submit/12356789

But act like this:
http:/mysite.com/program/submit/page.aspx?key=12356789

I wanted to pick up the 'key' query string and then go my merry way with it.

So with the URL routing I needed to setup some code in the Global.asax to tell it how to set up the identify and use the url:

void Application_Start(object sender, EventArgs e)
 {
   ....
   RegisterRoutes(System.Web.Routing.RouteTable.Routes);
 }

void RegisterRoutes(System.Web.Routing.RouteCollection routes)
 {

   routes.MapPageRoute(
   "View Page", // Route name
   "program/submit/{key}", // Route URL
   "~/program/submit/page.aspx" // Web page to handle route
   );
 }

Inside the Page.aspx Page_load I can pick up the 'key' value like this:

protected void Page_Load(object sender, EventArgs e)
 {
   if (IsPostBack)
    return;

   if (Page.RouteData.Values["key"] != null || Page.RouteData.Values["key"] != string.Empty)
 {
   string key = Page.RouteData.Values["key"].ToString();    //Request.QueryString["key"].ToString();
...
 }

Also, in pages that produce the user friendly url, I was able to build the url using the GetRouteUrl method:

string guid = "XXXX";
string url = Page.GetRouteUrl("View CIK", new { key = guid }); //returns: program/submit/1234567

So far it seems like I am not having any post back issues. So I think I'm liking this feature! So maybe I will set up a few more links as friendly urls sometime soon.

No comments:

Post a Comment