Using routing with webforms

Source: Internet
Author: User

In my last post I described how Routing no longer has any dependency on MVC. The natural question I 've been asked upon hearing that is"Can I use it with Web Forms?"To which I answer"You sure can, but very carefully."

Being on the inside, I 've had a working example of this for a while now based on early access to the bits. even so, Chris Cavanagh impressively beats me to the punch in blogging his own implementation of routing for Web Forms. nice!

One of the obvious uses for the new routing mechanic is as a "clean" alternative to URL rewriting (and possibly custom VirtualPathProviders for simple scenarios) for traditional/postback-based ASP. NET sites. after a little experimentation I found some minimal steps that work pretty well:

  • Create a custom IRouteHandler that instantiates your pages
  • Register new Routes associated with your IRouteHandler
  • That's it!

He took advantage of the extensibility model by implementingIRouteHandlerInterface with his ownWebFormRouteHandlerClass (not surprisingly my implementation uses the same name)

There is one subtle potential security issue to be aware of when using routing with URL Authorization. Let me give an example.

Suppose you have a website and you wish to block unauthenticated access toAdminFolder. With a standard site, one way to do so wocould be to drop the following web. config file inAdminFolder...

<?xml version="1.0"?><configuration><system.web><authorization><deny users="*" /></authorization></system.web></configuration>

OK, I am a bit draconian. I decided to block access toAdminDirectoryAllUsers. Attempt to navigate toAdminDirectory and you get an access denied error. However, suppose you use a naive implementationWebFormRouteHandlerTo map the URLFizzbucketToAdminDir like so...

RouteTable.Routes.Add(new Route("fizzbucket", new WebFormRouteHandler("~/admin/secretpage.aspx"));

Now, a request for the URL/FizzbucketWill displaySecretpage. aspxInAdminDirectory. This might be what you want all along. Then again, it might not be.

In general, I believe that users of routing and Web Form will want to secure the physical directory structure in which Web Forms are placed usingUrlAuthorization. One way to do this is to callUrlAuthorizationModule.CheckUrlAccessForPrincipalOn the actual physical virtual path for the Web Form.

This is one key difference between Routing and URL Rewriting, routing doesn' t actually rewrite the URL. Another key difference is that routing provides a mean to generate URLs as well and is thus bidirectional.

The following code is my implementationWebFormRouteHandler Which addresses this security issue. This class has a boolean property on it that allows you to not apply URL authorization to the physical path if you 'd like (in following the principalSecure by defaultThe default value for this property isTrueWhich means it will always apply URL authorization ).

public class WebFormRouteHandler : IRouteHandler{public WebFormRouteHandler(string virtualPath) : this(virtualPath, true){}public WebFormRouteHandler(string virtualPath, bool checkPhysicalUrlAccess){this.VirtualPath = virtualPath;this.CheckPhysicalUrlAccess = checkPhysicalUrlAccess;}public string VirtualPath { get; private set; }public bool CheckPhysicalUrlAccess { get; set; }public IHttpHandler GetHttpHandler(RequestContext requestContext){if (this.CheckPhysicalUrlAccess&& !UrlAuthorizationModule.CheckUrlAccessForPrincipa(this.VirtualPath,  requestContext.HttpContext.User, requestContext.HttpContext.Request.HttpMethod))throw new SecurityException();var page = BuildManager.CreateInstanceFromVirtualPath(this.VirtualPath, typeof(Page)) as IHttpHandler;if (page != null){var routablePage = page as IRoutablePage;if (routablePage != null)routablePage.RequestContext = requestContext;}return page;}}

You'll notice the code here checks to see if the page implementsIRoutablePageInterface. If your Web Form Page implements this interface,WebFromRouteHandlerClass can pass itRequestContext. In the MVC world, you generally getRequestContextViaControllerContextPropertyController, Which itself inherits fromRequestContext.

TheRequestContextIs important for calling into API methods for URL generation. Along withIRoutablePage, I provideRoutablePageAbstract base class that inherits fromPage. The code for this interface and the abstract base class that implements it is in the download at the end of this post.

One other thing I did for fun was to play around with fluent interfaces and extension methods for defining simple routes for Web Forms. since routes with Web Forms tend to be simple, I thought this syntax wowould work nicely.

public static void RegisterRoutes(RouteCollection routes){//first one is a named route.routes.Map("General", "haha/{filename}.aspx").To("~/forms/haha.aspx");routes.Map("backdoor").To("~/admin/secret.aspx");}

The general idea is that the route url on the left maps to the webform virtual path to the right.

I 've packaged all this up into a solution you can download and try out. The solution contains three projects:

  • WebFormRouting-The class library withWebFormRouteHandlerAnd helpers...
  • WebFormRoutingDemoWebApp-A website that demonstrates how to use WebFormRouting and also shows off url generation.
  • WebFormRoutingTests-A few non comprehensive unit tests of the WebFormRouting library.

WARNING: This is prototype code I put together for educational purposes. use it at your own risk. it is by no means comprehensive, but is a useful start to understanding how to use routing with Web Forms shoshould you wish.Download the demo here.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.