воскресенье, 30 августа 2009 г.

ASP.NET 4.0: WebForm Routing

NOTE: This is a quick introduction,. I’ll drill into this more in a future post.

One of the things we’re adding in ASP.NET 4.0 is built-in support for using Routing together with WebForms. Now, I’m totally aware that this is possible to do already and that a number of people have posted ways of doing this with the Web Routing feature which shipped with ASP.NET 3.5 SP1. We’re just adding some features to make it easier to do…

So, what are we adding?

  1. WebFormRouteHandler, this is a simple HttpHandler which you use in defining your routes…it essentially takes care of passing data into the page you’re routing to.
  2. Adding HttpRequest.RequestContext and Page.RouteData (this is really just a proxy onto the HttpRequest.RequestContext.RouteData object). Makes it easier to access information passed from the Route.
  3. ExpressionBuilders:
    1. RouteUrl (in System.Web.Compilation.RouteUrlExpressionBuilder), a simple way to create a URL corresponding to your route URL format within an ASP.NET Server Control
    2. RouteValue (again, in System.Web.Compilation.RouteValueExpressionBuilder), a simple way to extract information from the RouteContext.
  4. RouteParameter, a DataSource parameter which lets you easily pass data contained in RouteContext into a query for a DataSource…like FormParameter.

So, how does all this fit together?

WebFormRouteHandler

First, let’s define the new WebForm route…as follows:

public class Global : System.Web.HttpApplication

{

protected void Application_Start(object sender, EventArgs e)

{

RouteTable.Routes.Add("SearchRoute", new Route("search/{searchterm}", new WebFormRouteHandler("~/search.aspx")));

RouteTable.Routes.Add("UserRoute", new Route("users/{username}", new WebFormRouteHandler("~/users.aspx")));

}

}

As you can see, we simply map the Route onto a physical page (in the first string, “~/search.aspx”), we’ve also said that the parameter ‘searchterm’ should be extracted from the URL and passed into the page.

We also support an additional parameter for WebFormRouteHandler, the signature is as follows:

WebFormRouteHandler(string virtualPath, bool checkPhysicalUrlAccess);

The ‘checkPhysicalUrlAccess’ parameter specifies whether the RouteHandler should check the perrmissions for the physical page you’re routing to (in the case above, search.aspx) as well as the incoming Url…this defaults to ‘true’.

HttpRequest.RequestContext and Page.RouteData

Now that you’re in the physical page, how do you go about accessing the information which the Routing system has extracted from the Url (or, an object which some other object has added to the RouteData)?

As I mentioned before, we’ve added two methods…HttpRequest.RequestContext and Page.RouteData. Where Page.RouteData is just a convenience method onto HttpRequest.RequestContext.RouteData

This lets us do the following:

protected void Page_Load(object sender, EventArgs e)

{

string searchterm= Page.RouteData.Values["searchterm"] as string;

Response.Write(searchterm);

}

Here, we’re just extracting the value we passed in for ‘searchterm’ defined in the Route above.

Given the url http://localhost/search/scott/ , this would output the word ‘scott’ into the page…

So, nice…that’s how we’d do it in code…but what about Markup?

RouteUrl and RouteValue expression builders

ExpressionBuilders have been described as a ‘hidden gem of ASP.NET’, and that’s a shame…because they’re actually pretty cool. We’ve implemented two new expression builders for WebForm routing. They’re used as follows:

<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="<%$RouteUrl:SearchTerm=Bob%>">Link to searchasp:HyperLink>

Here we’re using the RouteUrl expressionbuilder to work out our Url based on a route parameter…the reason for doing this is to save having to hard code in our Url structure into our markup…this of course lets us change the URL structure later.

Based on the route we defined previously, this would generate the Url: ‘http://localhost/search/bob’, one thing to note is that we automatically work out the correct route based on the input parameters…you can also name the route in this expressionbuilder which lets you define a specific route url definition to use.

RouteValue is used like so:

<asp:Label ID="Label1" runat="server" Text="<%$RouteValue:SearchTerm%>" />

Pretty simple right? Yes, but it avoids you having to mess around with the more complex Page.RouteData[“x”] in your markup…

In this case we’d get the value ‘scott’ inserted into our label’s text element.

RouteParameter

Well, just use it like FormParameter e.g.,

<asp:sqldatasource id="SqlDataSource1" runat="server" connectionstring="<%$ ConnectionStrings:MyNorthwind %>"

selectcommand="SELECT CompanyName,ShipperID FROM Shippers where CompanyName=@companyname"

<selectparameters>

<asp:routeparameter name="companyname" RouteKey=”searchterm” />

selectparameters>

asp:sqldatasource>

I this case we extract the Route parameter ‘searchterm’ and pass it into the select statement.

Well, that’s it for this whistle-stop tour of our new ASP.NET 4.0 WebForm routing feature…

Комментариев нет: