UPDATES:
> Added some detail about routing with IIS7. See end of post![]()
> .NET 3.5 SP1 includes ASP.NET Routing as part of the framework. If you’re using ASP.NET AJAX (or anything else that uses resource handlers like WebResource.axd) be sure to check out this page. Without it you’ll find all resource requests go through to your page handler!![]()
> You can find a sample project and more details here.
> Be sure to check out Phil Haack’s post covering some of the security implications of this. I’ve also added a related comment to the end of this post![]()
> Added a new post that might help you resolve issues with relative file paths when using routes. Check it out here.
> Added a VB.NET sample project here! Thinking I need a new post to get all these updates under control![]()
> Added some SiteMap support here.
> Article on routing by Satheesh Babu here.
> ASP.NET 4.0 makes WebForm routing even easier; see Scott Guthrie’s post here.
The System.Web.Routing assembly introduced with .NET 3.5 SP1 (originally part of ASP.NET MVC) brings some interesting stuff for "traditional" ASP.NET developers. Check out this post by Phil Haack (and be sure to keep up with his upcoming posts that will go into more detail).
One of the obvious uses for the new routing mechanism 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!
The IRouteHandler implementation can be as simple or elaborate as you like. Just implement the GetHttpHandler method and return a new instance of an ASP.NET page (if you want to use an ASPX you can instantiate it with BuildManager.CreateInstanceFromVirtualPath).
Here’s a very simple IRouteHandler implementation that instantiates a single page (compiled or ASPX) for any request sent to it:
public class WebFormRouteHandler<T> : IRouteHandler where T : IHttpHandler, new() { public string VirtualPath { get; set; } public WebFormRouteHandler( string virtualPath ) { this.VirtualPath = virtualPath; } #region IRouteHandler Members public IHttpHandler GetHttpHandler( RequestContext requestContext ) { return ( VirtualPath != null ) ? (IHttpHandler)BuildManager.CreateInstanceFromVirtualPath( VirtualPath, typeof( T ) ) : new T(); } #endregion }
This example could be useful in a site with a single ASPX that hosts multiple ASCXs as its "pages" (maybe one that uses the inbuilt SiteMap as a mapping mechanism between public URLs and ASCXs). For more traditional sites, your GetHttpHandler would return separate page instances based on the RequestContext it’s provided with (RequestContext includes the routing details extracted from the URL; MVC would create a Controller at this point).
Routes are usually registered in the Application_Start handler in Global.asax. Here’s a simple example based on the "single ASPX / multiple ASCX" approach that passes several routes to a single page (MyPage.aspx):
protected void Application_Start( object sender, EventArgs e ) { RegisterRoutes( RouteTable.Routes ); } public static void RegisterRoutes( RouteCollection routes ) { // Note: Change the URL to "{controller}.mvc/{action}/{id}" to enable // automatic support on IIS6 and IIS7 classic mode var routeHandler = new WebFormRouteHandler<Page>( "~/MyPage.aspx" ); routes.Add( new Route( "{page}", routeHandler ) ); routes.Add( new Route( "AccountServices/{page}", routeHandler ) ); routes.Add( new Route( "Default.aspx", routeHandler ) ); }
Phil Haack has a post that covers some security implications of this approach. Like Phil suggests, the ‘insecure’ behavior might be exactly what you want. You could prevent direct URL access to your ASPX’s (using ASP.NET’s existing mechanisms) and consider them just resources to be used by your IRouteHandler.
Also note that Phil includes a mechanism for passing the RequestContext to your page (just define and implement the IRoutablePage interface).
Routing in IIS6
By default IIS6 only passes certain requests to ASP.NET (.ASPX, .ASMX. ASHX etc). To allow the routing mechanism to handle your requests you need to set up “Wildcard Application Mapping” for your application. This causes ALL requests to your site (even static file requests) to go through ASP.NET. This isn’t as bad as it sounds, but if you’re wanting to squeeze every last drop of performance from your app, IIS7 might be a better option.
You can find details on setting up Wildcard Application Mapping here on TechNet.
Routing in IIS7
To use all this goodness in IIS7, there are a couple of extra steps you need to take (instead of the "wildcard mapping" needed in IIS6):
- Derive a concrete class from UrlRoutingHandler. Something like this:
/// <summary> /// Simple UrlRoutingHandler implementation /// </summary> public class RoutingHandler : UrlRoutingHandler { protected override void VerifyAndProcessRequest( IHttpHandler httpHandler, HttpContextBase httpContext ) { } }
- In web.config, under <modules> inside <system.webServer>, add this:
<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
- Also under <modules> you’ll need to add a new attribute if you want Session state to work:
<modules runAllManagedModulesForAllRequests="true">
- Finally, under <handlers> (inside <system.webServer> again), add a reference to the RoutingHandler we just defined (remember to change the SimpleRoutingTest namespace and assembly name to your own):
<add name="UrlRoutingHandler" preCondition="integratedMode" verb="*" path="UrlRouting.axd" type="SimpleRoutingTest.RoutingHandler, SimpleRoutingTest"/>
That should be all you need
Hope this helps!


193 comments
Comments feed for this article
March 11, 2008 at 11:11 pm
Haacked
Great stuff! I posted my own implementation of this I’ve been working on. One thing to be aware of is it is possible to have multiple routes route to the same page. This could get around url auth on accident if you’re not careful.
March 12, 2008 at 12:55 pm
Using Routing With WebForms
[...] 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. [...]
April 10, 2008 at 7:28 am
mrsvierkant
I think I’m better off sticking with Sesame Street, LOL!
April 25, 2008 at 4:29 pm
System.Web.Routing with WebForms sample « Chris Cavanagh’s Blog
[...] Comments Since my earlier post on using the System.Web.Routing assembly with traditional WebForms (here), I’ve had some requests for a sample project to show it in action. You can get the [...]
May 16, 2008 at 7:25 am
dmitry39
thx, great stuff. First result in google for request “System.Web.Routing”. It’s that what i need.
Regards from Russia
June 21, 2008 at 9:03 am
Mike Ormond's Blog : ASP.NET Routing and Authorization
[...] Chris and Phil got there before me so I recommend reading those posts but essentially we would add an additional check as part of the route handler that checks whether the current user is authorised to view the requested path by calling UrlAuthorizationModule.CheckUrlAccessForPrincipal(). Thus, my code that I originally posted back here could be modified along the following lines: [...]
July 23, 2008 at 1:21 am
Net framework programmer
We are using System.Web.Routing.dll as
for example we route to following url’s:
{CustomerCity}/News/
(site url: ‘http://localhost:1979/Lazurit/Kaliningrad/News/’)
{CustomerCity}/News/{NewsItem}/
(site url: ‘http://localhost:1979/Lazurit/Kaliningrad/News/Lazurit1in3/’)
virtual path of site: /Lazurit
it works great. But how we can route to root url. When we try to route
(“/” or “”) it does not works. We need to route to
‘http://localhost:1979/Lazurit/’ (it is a root url) We need to
determine user city by ip address. After that we will redirect user to
‘http://localhost:1979/Lazurit/UserCity’. Is it real to create route
for ‘http://localhost:1979/Lazurit/’? We are creating CMS system for
it. Our main page is located in ‘Pages’ folder and has name
‘Main.aspx’. We need to create route ‘http://localhost:1979/Lazurit/’
to ‘http://localhost:1979/Lazurit/Pages/Main.aspx’.
We are using IIS 6 and asp.net 3.5 sp1
August 11, 2008 at 3:38 pm
Using System.Web.Routing with Castle MonoRail at ILM Community Blog
[...] folks have already posted about using System.Web.Routing with standard ASP.NET WebForms, and I’d like to extend [...]
August 28, 2008 at 9:35 pm
Chris Cavanagh
“Net Framework programmer” / progblog – Sorry I missed your post until now
Are you still having problems with the routing or did you get it figured out?
September 3, 2008 at 12:01 am
Just Another Coder » Blog Archive » URL Routing, ReportViewer and Site Map Navigation
[...] of ASP.Net MVC fame). It's already been covered well—read about URL routing here, how to implement it for web forms, and this too. Naturally I found a nail to match my new URL Routing [...]
September 4, 2008 at 7:01 am
Net Framework programmer
thx for reply Chris. We have found solution.
September 3, 2009 at 10:18 am
riz
what’s the solution please? I’m having the same problem.
September 26, 2008 at 12:38 am
Parthasarathy
how can i implement asp.net routing in my WCF service? is it possible?
September 26, 2008 at 9:32 am
Chris Cavanagh
Parthasarathy – Could you give an example of what you’re hoping to achieve?
There’s an overview of some 3.5 SP1 WCF changes here: https://www.gazitt.com/blog/PermaLink,guid,dd5a7066-d288-48ef-91a8-af895fecbe8c.aspx. There’s improved REST support, but I’m not sure if that helps you or not
September 27, 2008 at 4:17 am
Ronny
Hi Chris,
Thanks for the great sample
I havent been doing much asp.net for some time and now I’m about to “re-do” my old 2.0 url rewriting stuff and that lead me here.
I have one slight off-topic thing that I am currious about: I noticed that your sample project is not a “standard” web site project – any paticular reason for that?
Cheers,
Ronny
September 27, 2008 at 5:18 pm
Chris Cavanagh
Ronny – It’s been a while since I published it; what’s not standard about it? (would be surprised if it wasn’t just a web site project, but it’s not unknown for me to be wrong
)
September 27, 2008 at 7:27 pm
Ronny
It looks like it has been added as an “ASP.NET Web Application”, what I’ve normally done is to add a “new website” to a solution.
The difference that I can see so far is that with a “normal website” code is auto compiled and with a “web application” it is not.
The way I noticed this was I was not able to add the Global.asax.cs class to the root of my web site (you know so it is nested with the Global.asax file) – also namespaces are not used for pages in a “normal website”.
I guess the differences are subtle, but I was just currious
Maybe I’ve been away for a long time and this was somehow the “new” way of doing things.
Sorry for being a little long-winded and thanks for you reply.
September 27, 2008 at 7:33 pm
Ronny
I just did a quick search on this, I guess I just have a bad memory hehe
This was introduced with VS2005 at some point, I found a post at Scott’s blog describing it here: http://weblogs.asp.net/scottgu/archive/2005/12/07/432630.aspx
September 27, 2008 at 8:42 pm
Chris Cavanagh
Ronny – Web App Projects basically just re-introduced VS.NET/2003′s ASP.NET projects into VS2005 (Web Site Projects weren’t a great option for migrated projects back then). Still, I’m surprised I didn’t make this a Web Site Project
You’ll probably find it cleaner to create a new web site project and just take ideas / snippets from the sample…
October 17, 2008 at 8:26 am
prabhjot singh
i am working on a concept of making URL routing work in the project which i converted from VS2005
to VS2008. Firstly i have made all the required changes in the global.asax file and the site root as well. The data is going in the route table but the page is not getting displayed in the browser with the mapped URL. It says “cannot locate the following page”, and secondly it is also not loading the global.asax file. what should i do?
October 17, 2008 at 9:59 am
Chris Cavanagh
Prabhjot – What type of project did it convert to? (specifically, web site project or web app project). Also, are you testing/debugging in IIS or VS’s webserver? If you prefer, you can mail me some files and I’ll take a closer look
You could try creating a new project in VS2008 (or use my sample) to test / prove the concepts, and then compare that directly with your own [converted] project. I often find that’s the easiest way to diagnose stuff like this.
Hope this helps!
October 17, 2008 at 10:13 pm
prabhjot singh
sir, it got converted to a website project and i am testing and debugging in VS’s webserver.
Thanks a lot sir
October 18, 2008 at 4:30 pm
Chris Cavanagh
Prabhjot – I’ve updated my sample project here: http://chriscavanagh.wordpress.com/2008/10/18/aspnet-routing-revisited-again/ (source is also available on CodePlex).
Could you confirm the appropriate web.config settings are in your project? (compare to my sample code). It needs to register a couple of things for the routing handler to catch requests.
October 20, 2008 at 7:04 am
shikha
hello
thanks for the sample project.it was helpful.
But according to your sample code you have given
Search page:
But what if i want to give dynamic value links like
hello
how the pathh is going to map
Thanks
October 20, 2008 at 7:05 am
shikha
hello
thanks for the sample project.it was helpful.
But according to your sample code you have given
Search page:<activelink…etc
But what if i want to give dynamic value links in anchor tag
how the pathh is going to map
Thanks
October 20, 2008 at 1:02 pm
Chris Cavanagh
shikha – Could you give me a bit more detail about what you’re wanting to achieve?
The RoutablePage base class in my sample includes a GetVirtualPath helper method. It allows you to dynamically construct URLs based on the currently defined routes (either using a specific named route, or a “best match”). You can see an example of its use in http://www.codeplex.com/ASPNET35Routing/SourceControl/FileView.aspx?itemId=204614&changeSetId=12901 .
The last argument to GetVirtualPath is an anonymous type containing key/value pairs to subtitute in the URL (internally it calls http://msdn.microsoft.com/en-us/library/cc679806.aspx ).
Let me know if this helps
(or not; I can always add more detail).
October 21, 2008 at 5:03 am
shikha
hello
i have implimented the url routing for dynamic and ststic also
.But the javascript and css which are present on the
different folders of same project .and called on the aspx pages are not calling these javascript and css.
could you plz help me out with this
Thanks
October 21, 2008 at 1:18 pm
Chris Cavanagh
shikha – This issue is a result of the way browsers resolve relative paths. By default they’re based on the URL of the requested page. In the case of routing, the path the browser requests [for a page] doesn’t necessarily correspond to the physical location of the page on the server. When the browser tries to request the css/js resources based on this URL, it won’t be able to find them…
There are a few ways to solve this:
1) Include your CSS content in your theme folder (App_Themes/MyTheme). ASP.NET should automatically add the relevant references.
2) Include all your Javascript (and CSS if not using themes) in a Master Page in the application root. Paths to Javascript and CSS will be relative to the Master Page location.
3) Set the HTML ‘BASE’ element in your page (http://www.w3.org/TR/REC-html40/struct/links.html#h-12.4). It’s possible to set this dynamically with a little codebehind (or embedded code).
4) Try adding a route (in Global.asax) for .js and .css files and see if there’s a programmatic way to serve them up (not sure if this is possible; I’ll take a look).
Hope this helps (hopefully one of these ideas will work!
).
October 21, 2008 at 1:27 pm
Chris Cavanagh
shikha – You can also use things like RegisterClientScriptInclude and RegisterClientScriptResource to serve up your script (through WebResource.axd). Take a look at these:
http://msdn.microsoft.com/en-us/library/kx145dw2.aspx
http://bytes.com/forum/thread606473.html
Note you’ll probably need to uncomment some lines in Global.asax [see my sample] to prevent .axd’s being routed inappropriately.
October 21, 2008 at 1:35 pm
ASP.NET Routing revisited (again) « Chris Cavanagh’s Blog
[...] 18, 2008 · 1 Comment I’ve updated my ASP.NET 3.5 + System.Web.Routing sample based on some great feedback and questions. It’s much simpler and gives a better [...]
October 22, 2008 at 2:04 am
prabhjot singh
sir,
Thanks for the sample project.
now the scenerio is something like this:
1. All my pages are in the one folder.
2. My static and dynamic routing is working.
If i click on the page on which i haven’t implemented routing, that page is displayed, but when i again click onto the page that uses routing, the url which is shown is incorrect and the page is not getting displayed.
eg
my folder name is abc
my site name is mysite
i have done like this
<url =”~/abc/index.aspx”
for this the url which is displayed is
mysite/index
now when i click on the page working without routing eg home. It opens up
when i again click onto index page , the url it shows is
mysite/abc/index. it picks up folder name as well, which should not happen.
Coding in the global.asax is just fine and according to your project.
Please suggest something.
October 22, 2008 at 2:14 am
prabhjot singh
sir,
Thanks for the sample project.
now the scenerio is something like this:
1. All my pages are in the one folder.
2. My static and dynamic routing is working.
If i click on the page on which i haven’t implemented routing, that page is displayed, but when i again click onto the page that uses routing, the url which is shown is incorrect and the page is not getting displayed.
eg
my folder name is abc
my site name is mysite
i have done like this
anchor tag=”index”
<url =”~/abc/index.aspx”
for this the url which is displayed is
mysite/index
now when i click on the page working without routing eg home. It opens up
when i again click onto index page , the url it shows is
mysite/abc/index. it picks up folder name as well, which should not happen.
Coding in the global.asax is just fine and according to your project.
Please suggest something.
October 22, 2008 at 5:35 am
Chris Cavanagh
prabhjot – How are you generating your URLs? Are you using the GetVirtualPath helper with a named route?
Any possibility of sending me a sample project so I can debug it?
October 22, 2008 at 5:48 am
prabhjot singh
sir, I am using the GetVirtualPath helper with named route only. I am using the same concept as you did in your sample project.
But the URL generated is not correct when i go back to the index page, and the page is not displayed. the url generated is
mysite/abc/index rather than
mysite/index
please suggest a solution.
sir you have been immensily helpful and i thank you.
October 22, 2008 at 6:54 am
Chris Cavanagh
prabhjot – Could you paste some code for me to look at? I’d be interested in seeing the routes you’ve configured and the parameters you’re passing to GetVirtualPath.
Thsnks!
October 22, 2008 at 7:21 am
prabhjot singh
sir, this is the coding i’ve done in the index page.
objStringBuilder.Append(““);
This i have written in the global.asax file
var searchhandler = new WebFormRouteHandler(“~/Logged/index.aspx”);
routes.Add(new Route(“index”, searchhandler));
This i have written in the master page coding
Home
sir, is it possible i take out all the .aspx pages from the folder and put them directly in the root directory. will that work fine ?
The WebFormRootHandler is the same which you have used in your sample page.
Thanks.
October 22, 2008 at 7:24 am
prabhjot singh
sir the coding part is not getting displayed properly
i don’t know wt to do
October 22, 2008 at 7:41 am
Chris Cavanagh
prabhjot – No worries about how the code appears on this page; all comments get emailed to me and look fine…
Could you email your project to blog@chriscavanagh.com?
I think the problem is with the anchor tag you have in the Master Page; it looks like you’re using just “index” as the relative path. See my response to shikha above; the browser will try to create a URL based on the current request with “index” at the end (it doesn’t understand anything about server routing itself, so makes the best guess it can). Try generating your ‘home’ anchor like this:
October 22, 2008 at 7:43 am
Chris Cavanagh
I hit the same comment posting problem
Trying again…
ActionLink( GetVirtualPath( “index”, null ), “Home” )
October 22, 2008 at 11:05 pm
prabhjot singh
hello sir,
i have defined my relative paths in the master page itself. like for index page i have written
anchor tag= “index”
without routing it was
anchor tag= “index.aspx”
in the master page i can’t call the ActionLink method. Rest of the coding i have done in the Global.asax file, same as your sample project.
i sent you the sample code y’day.
Is there something i can do?
October 22, 2008 at 11:25 pm
Chris Cavanagh
prabhjot – Actually you *can* call page methods from the Master page. If you make the ActionLink and GetVirtualPath methods in RoutablePage public (or internal if you prefer), then add something like this to your Master Page (either server script or codebehind):
protected new SimpleRoutingTest.RoutablePage RoutablePage
{
get { return Page as SimpleRoutingTest.RoutablePage; }
}
Then use it like this in your master page:
= RoutablePage.ActionLink( RoutablePage.GetVirtualPath( “index”, null ) )
Unfortunately I didn’t get your sample project
(maybe my email server blocked it). Howabout uploading it to Codeplex or Google Code?
October 23, 2008 at 1:52 am
prabhjot singh
sir, now i have written something like this
<a href=”"”> Home
in the master page
protected new abc.RoutablePage RoutablePage
{
get { return Page as abc.RoutablePage; }
}
The error which it shows is in the master page is
Object reference not set to an instance of an object.
October 23, 2008 at 9:49 am
prabhjot singh
sir,
i’ll send you my sample project
October 24, 2008 at 2:28 pm
Leigh
A superb blog!
It’s all up and running nicely for me in my current project, but I do have the following queries:
1) How can I access the RouteData from the master page? I have a control on the master page that used to use parameters from the querystring, but now it needs to retrieve the values from RequestContext.RouteData. How can I achieve this?
2) My sitemap driven navigation has stopped working. For example, my sitemap contains an entry for “/forumthread.aspx”. “/forumthread.aspx?fid=123&tid=456″ used to correctly highlight the associated forumthread.aspx node in the navigation tree. This url for this page is now “/forum/123/thread/456″. I have no idea how to translate this into something that can go in the sitemap, as the 123 and 456 values are determined at runtime. Any ideas?
Thanks for such an informative post.
October 24, 2008 at 9:12 pm
Chris Cavanagh
Leigh – Thanks for the feedback
1) If you’re using the RoutablePage base class, it already holds a reference to the RequestContext (IRoutablePage has a ‘set’ property). The simplest solution is add a public getter for RequestContext (or specifically RouteData if you prefer). In your Master Page you can then just use ( Page as RoutablePage ).RequestContext.RouteData ….
although it takes a little coaxing. Check back here in the next few days; I’ll be posting something that should help.
2) The SiteMap mechanism already supports routing pretty well
October 27, 2008 at 5:36 am
Leigh
Thanks for the pointer Chris.
I look forward to your next blog
I’m soooo glad I found your site! It’s made my life so much easier…
November 3, 2008 at 6:45 am
prabhjot
hello sir
i m nevigating the url from master page.
as you have given us the follwoing code to user Routerpage class
protected new SimpleRoutingTest.RoutablePage RoutablePage
{
get { return Page as SimpleRoutingTest.RoutablePage; }
}
Then use it like this in your master page:
= RoutablePage.ActionLink( RoutablePage.GetVirtualPath( “index”, null ) )
i have used this and in global.aspx
i have set the path like
routes.Add( “index”, new Route( “index”, new WebFormRouteHandler( “~/Log/index.aspx” ) ) );
But on building the solution it is giving me object refrence null.
can u plz suggest .what the point we are missing here.
thanks
November 3, 2008 at 7:01 am
Leigh
>The SiteMap mechanism already supports routing pretty well, although it takes a little coaxing
Are there any existing sites that detail what is required to get SiteMaps working with (for example) “/forum/123/thread/456″?
Thanks
November 3, 2008 at 7:24 am
prabhjot
respected sir,
i have menus in my master page which get implemented with CSS files, but when i execute my project the following error is displayed, object reference not found at
= RoutablePage.ActionLink( RoutablePage.GetVirtualPath( “index”, null ) )
please suggest something
regards
prabhjot singh
November 7, 2008 at 2:49 am
ASP.NET Routing + just enough rope « Chris Cavanagh’s Blog
[...] 6, 2008 · No Comments If you’ve played with the new ASP.NET routing stuff with WebForms, you probably encountered some issues with relative paths to static content (css, Javascript files [...]
November 11, 2008 at 2:57 am
prabhjot Singh
Respected sir,
I am highly grateful to you, you have been immensely helpful, as you said about the path of CSS and Js are exactly coming as you said with the funky URL we have used for routing. Can you plz be more clear about where should i put the base URL function or where i can define the exact path of CSS and Js as i am not using themes.
Secondly, iam also facing the issue of dynamically generated path in XML e.g.
iam generating dynamic links in XML for my pages
Thirdly, In global.asax we have defined routable Url with given id’s, but sometimes it picks the wrong id’s , to be very precise it picks the name of my js files.
suggest something as iam stuck here.
regards and i obliged
prabhjot singh
November 14, 2008 at 1:04 am
Pawan
HI Chris,
I m new to you site and i m using your contents you provided and thank you so much for providing such a great help.
Right now i m facing an issue related to url routing.
how do i rout the links which i dynamically created in javascript functions.is there anyway for this.please can you provide me any coding stuff for that.
thanx
pawan
November 14, 2008 at 8:05 am
Chris Cavanagh
Pawan – Could you send me some sample code to look at? (I’d like to see how you’re currently generating the links).
It’d be great if you could also send me an outline of your site structure (folders etc) and sample URLs you’d “like” to use…
November 17, 2008 at 11:46 pm
Mike
Hi, thank you for the post.
I am able to get routing working using a small test site and the VS 2008 webserver. However, when I setup a virtual server in IIS and change my site in VS to debug with that webserver, I am unable to get the routing to work. I can’t even hit a breakpoint in Application_Start. In my browser I get a page cannot be found error, since the URL isn’t to a real page. Do you have any suggestions? Thanks!
Mike
November 18, 2008 at 1:10 am
Chris Cavanagh
Mike – Which version of IIS are you using? This post includes some IIS7 details, but if you’re using IIS6 you’ll need to set up a “wildcard mapping”…
Try this page and let me know if it helps:
http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/5c5ae5e0-f4f9-44b0-a743-f4c3a5ff68ec.mspx?mfr=true
November 18, 2008 at 5:43 pm
Mike
I am actually using IIS 5.1 in XP. I’ll need to save this project for another day I think, when I can setup a 6.0 or 7.0 server. Thanks.
November 18, 2008 at 8:50 pm
Chris Cavanagh
Mike – I’ve not tried this in IIS5, but if it supports wildcard application mapping it should work fine (basically it routes EVERY request through ASP.NET; you need to uncheck “check if file exists” so that it doesn’t assume the URL relates to a physical file).
November 19, 2008 at 3:36 am
Leigh
>The SiteMap mechanism already supports routing pretty well although it takes a little coaxing. Check back here in the next few days; I’ll be posting something that should help.
Hi Chris. Are you still planning to blog on this?
November 19, 2008 at 11:10 pm
Chris Cavanagh
Leigh – Thanks for the reminder! I still plan to post something
As I recall, the can have your “routed” url (in its ‘url’ attribute) but I need to look again at how it handles parameters passed as path elements. The “coaxing” I mentioned might involve a custom SiteMapProvider.
November 20, 2008 at 6:16 am
prabhjot Singh
respected sir,
Thanks for helping me all through. My site is up and running with the clean URL concept and it looks really great.
Sir , one last thing which i wanted to ask from you is that, if i am using a mehod e.g.
abc.aspx?ID=&View=inc”)
how will i convert this thing into routable format, i mean what i have to write? I have written this code in the client side.
prabhjot singh
November 20, 2008 at 6:54 am
Chris Cavanagh
Hi Prabhjot – One way might be to use the server-side URL helper functions to create a “base” URL and put that into the page, then create the “real” URL client-side. So something like this on the server-side (note I’ve replaced angle brackets with [ and ] so I can type them here:
…[div]
[script type="text/javascript"]
var baseUrl = “[%= GetVirtualPath( null ) %]“;
var realUrl = baseUrl + “/inc”;
[/script]
[/div]
(Hope this is readable! I might need to code up a sample of this too
)
November 21, 2008 at 12:18 pm
Jim
Chris,
Similar to Mike’s issue, I am trying to get routing to work on IIS 6 after having it work on my box with IIS 7. I looked at the Microsoft page you referred Mike to, but I am unsure *which* DLL I am suppose to specify when adding the wildcard mapping. Is it a system one? One of my own?
Thanks,
Jim
November 21, 2008 at 3:00 pm
Chris Cavanagh
Jim – You need to point it to the ASP.NET ISAPI extension, typically located here:
c:\windows\microsoft.net\framework\v2.0.50727\aspnet_isapi.dll
Hoep this helps!
November 21, 2008 at 5:19 pm
Jim
Chris,
Thanks for the response. One last question.
One additional thing I wanted to do was to have the served file (a PDF in this case) to appear to come from a sub folder in the web site. Now, if I add the filter to the top level of my site (I specifically tried an application extension and not the wild card), it works, but I can’t then serve up any real unsecured PDF. So, I created a folder with the same name as where the route SAYS it is coming from and put the filter there. Now when I try and access the special PDF, I get a connection error in IE and Firefox does nothing.
If you have any clues, I would appreciate a push in the correct direction.
Thanks,
Jim
November 23, 2008 at 11:12 am
prabhjot
hi chris,
Thanks for your response,
Iam still stuck with the databinder issue.
the code i have written is something like this
‘[%#DataBinder.Eval(Container.DataItem,"id")%].
Secondly, if iam using handlers in my project, how can i convert them into routable format, it will be good if you post a sample project.
prabhjot singh
November 24, 2008 at 11:28 am
Jim
Chris,
OK, I figured it out/made a work around. Since my secured pdf will always be routed with one static name, I simply added a new route to handle generic PDF files and have it serve them up.
Thanks for a great article.
Jim
November 26, 2008 at 5:36 am
Leigh
>Leigh – Thanks for the reminder! I still plan to post something
Glad to hear that. The SiteMap aspect of routing is causing me some problems…
December 2, 2008 at 6:53 am
prabhjot
hi chris,
i am back again, thanks for your help.
sir, i am using IIS6, i am using wild card mapping concept, but it has scalability problem, i want to shift to 404 approach(extension less routing)
I have implemented everything , i have changed the custom errors. i have written the required code in the global file. but when i run it on the server it shows “The resource cannot be found.”. what more should i do?
Regards
Prabhjot
December 2, 2008 at 7:08 am
Chris Cavanagh
Prabhjot – Phil Haack recently blogged about this (relative to MVC, but same basic issues). Let me know if it helps: http://haacked.com/archive/2008/11/26/asp.net-mvc-on-iis-6-walkthrough.aspx.
December 2, 2008 at 8:29 am
prabhjot
But i have made my project without using the MVC approach.
Thanks
prabhjot
December 7, 2008 at 10:54 am
Mike
What about Session state? Any page I access via a route looses it’s Session. I’ve tried both your and Phil’s version but Session is always null. All pages accessed directly without a route have Session fine. Any thoughts?
Thanks-
December 7, 2008 at 9:56 pm
Chris Cavanagh
Mike – I’ll look into this. I’ve not had this problem before though; could you send me a small sample project?
December 11, 2009 at 4:16 pm
Adam
I’m having the same problem Mike. Did you manage to solve it? It may be IIS 7.0 related as Session is available when run on our IIS 6.0 development machine. Other developers who also use IIS 6.0 also have no problems.
December 11, 2009 at 7:45 pm
Chris Cavanagh
Adam / Mike – Check the end of this post:
http://www.codewrecks.com/blog/index.php/2009/10/28/aspnet-routing-problem-with-iis7-and-integrated-pipeline/
Not sure if related, but worth a shot
December 7, 2008 at 9:59 pm
Chris Cavanagh
Prabhjot – Phil’s post was about getting IIS6 working with ASP.NET’s routing (regardless of whether using MVC or not). Any progress getting it working?
December 15, 2008 at 8:21 am
Zakhar
hi chris. Could you please tell me, how can i do next: i need to change navigate url depends on route data. For expample:
Route rt3 = new Route(“Treeview/{advert}/{variant}/FunctionTree”, new WebFormRouteHandler(“~/WebForm2.aspx”));
rt3.Defaults = new RouteValueDictionary(new { stage= “1″, variant = “1″ });
rt3.Constraints = new RouteValueDictionary(new { stage= @”\d{1,2}”, variant = @”\d{1,2}” });
//rt3.GetRouteData(HttpContext.Current);
routes.Add(rt3);
I need to change url if the parameter “stage” is equal to “12″ for example. “~/webform3.aspx”. How can i do this? Thanks in advance.
December 15, 2008 at 10:28 am
Chris Cavanagh
Zakhar – Could you confirm what you mean by “change url”? If you’d just like “stage=12″ to be handled by another RouteHandler, then you could just add another route, something like this (I’m guessing “advert” should be “stage” in your example?):
var rt4 = new Route( “TreeView/12/{variant}/FunctionTree”, new WebFormRouteHandler( …..
I haven’t tested this though. Let me know if I’m barking up the right/wrong tree
December 19, 2008 at 5:28 am
Leigh
Possibly a stupid question, but how/where do I catch the SecurityException that is thrown in GetHttpHandler? I want to simply display a message informing the user that they do not have permission to view the page. Ideally, I’d like to catch it one, in my MasterPage (rather than in each individual page).
January 12, 2009 at 9:54 pm
Chris Cavanagh
Leigh – Are you still looking for a solution to this? (sorry for my slow reply btw).
December 23, 2008 at 11:18 am
Samuli Lintunen
Leigh,
I replaced the tad ambiguous SecurityException with a HttpException and
gave it the http response status code of 401 “Unauthorized” (http://en.wikipedia.org/wiki/List_of_HTTP_status_codes#4xx_Client_Error). The reasoning being that since routing belongs to the System.Web namespace (System.Web.Routing) and System.Web (http://msdn.microsoft.com/en-us/library/system.web.aspx) deals with http-related things as does the GetHttpHandler; throwing a (401) HttpException is acceptable, perhaps more desirable than a generic SecurityException in the context of
checking user permissions on the web. The HttpException is then handled at the application level in global.asax.cs in the Application_Error section according to its status code.
You might want to check out the following link:
http://stackoverflow.com/questions/55961/exception-handling-in-net-web-apps
January 12, 2009 at 8:51 pm
pankaj
Hi Chris, I am using the .net 3.5 SP1′s url re-routing and having some issues with virtual path of the web application.
If the virtual path in the web project’s property (in VS ’08) is set to ‘/’, then things work just fine, but when I changed the value to ‘/My.WebApp’, the url re-routing fails and I get a 404 – The resource cannot be found.
Here is the route that I am registering:
RouteTable.Routes.Add(new Route(“{PartnerName}/RegisterUser”, new MyRouteHandler(“~/RegisterUser.aspx”)));
This is the url on the browser with virtual path = ‘/’
http://localhost:1622/panasonic/registeruser.aspx
and this is the one with virtual path = ‘/My.WebApp’
http://localhost:1622/My.WebApp/panasonic/registeruser.aspx
Any help is greatly appreciated.
January 12, 2009 at 9:50 pm
Chris Cavanagh
pankaj – Have you tried running the site under IIS? I haven’t [yet] tried routing with Visual Studio’s webserver using a different (not “/”) virtual path. It doesn’t completely surprise me there are a couple issues though. It’ll probably need some more experimentation to get right (I’ll look into it as soon as I can).
What’s the reason you’re needing a different path in Visual Studio? You should find the site works great running directly in IIS, but let me know if you’ve found otherwise…
Hope this helps!
January 13, 2009 at 11:52 am
pankaj
Chris, the site does not work even in IIS when deployed under a virtual directory.
Although, my lucky stars, we found the solution. If I register the routes as (notice the .aspx in the first param of Route’s ctor)
RouteTable.Routes.Add(new Route(”{PartnerName}/RegisterUser.aspx”, new MyRouteHandler(”~/RegisterUser.aspx”)));
things work great, except now I also have to type in the file extension in the url…but I am not complaining.
January 14, 2009 at 3:11 pm
Paolo
Thanks Chris, the version in VB.net?
January 14, 2009 at 4:06 pm
Chris Cavanagh
Hi Paolo – Yes I’d love a VB.Net version! You wanna write it for me?
But obviously, a very good point. It’s now on my todo list
January 15, 2009 at 8:54 am
Paolo
Hello Chris, I tried to convert it to VB but I have an error in the classroom.
the error is here: Implements IRouteHandler.
Sorry for English, but I am an Italian. Hello
January 16, 2009 at 8:55 am
Chris Cavanagh
Hi Paolo – What’s the error you’re getting? (the IRouteHandler interface is defined in System.Web.Routing, so make sure you have a reference to that).
January 18, 2009 at 10:40 am
What is the version of the Integrated Server (VS Studio 2008 SP1) | keyongtech
[...] having to create tons of routing rules. > Yes I followed a tutorial on Chris Cavanagh’s blog (http://chriscavanagh.wordpress.com/2…url-rewriting/) and I can’t get it to work on VS Studio 2K8 (both Express and Pro). The Routing handler never [...]
January 19, 2009 at 5:44 pm
Paolo
Hello Chris, thanks for the help.
I used the tool to convert developerfusion.com in vb.net: http://www.developerfusion.com/tools/convert/csharp-to-vb/
but the example does not work. The class is not used in the code region
January 20, 2009 at 12:38 am
Chris Cavanagh
Paolo – No worries; I’ve created a VB.NET sample project for you
Check out my post here:
http://chriscavanagh.wordpress.com/2009/01/20/aspnet-routing-in-vbnet/
Let me know if any problems!
February 17, 2009 at 8:32 am
Leigh
Thanks Samuli
I took your advice and switched to throwing an HttpException. It’s all working perfectly and cleanly. I appreciate your help, as this was something I didn’t know how best to handle.
February 24, 2009 at 4:29 am
Leigh
Has anyone managed crafted a routing aware sitemap for this stuff? My next project needs to be sitemap based, so I might have to drop routing
February 25, 2009 at 4:29 pm
Chris Cavanagh
Leigh – I’ve successfully used sitemaps with routing (through a custom SiteMapProvider). However my use cases were unusual / weird
This may be a better example…:
http://blog.maartenballiauw.be/post/2008/08/29/Building-an-ASPNET-MVC-sitemap-provider-with-security-trimming.aspx
February 26, 2009 at 5:12 am
Leigh
Thanks for the link Chris. I’ll take a look now…
February 27, 2009 at 8:01 am
Prk
Hi.
I just installed VWD with .net framework 3.5 and it seems that the System.Web.Routing is not included as c# tells me.. what should i do?
February 27, 2009 at 9:27 am
Chris Cavanagh
Prk – Make sure you install .NET 3.5 Service Pack 1. That should include the routing assemblies
March 4, 2009 at 12:51 am
GK
Hi,
I have created project which implemented URL routing using System.Web.Routing.
Everything is working fine. Now i got problem is,
i created a page with server side button. On button click, i am doing something. Initially URL is fine like http://localhost:2263/TestRouting/show/markets/1 but when button is clicked, the address bar shows the actual aspx like http://BaseURL/markets/test.aspx?section=markets&pageno=1
How to retain the same URL in address bar like http://localhost:2263/TestRouting/show/markets/1 instead of showing actual .aspx.
Please help, looking for your suggestion….
March 4, 2009 at 1:10 am
Chris Cavanagh
GK – If you put a breakpoint in your WebFormRouteHandler, does it get hit? Sounds like there’s a Response.Redirect happening somewhere (or some old rewriting code) rather than using routing…
March 8, 2009 at 9:25 am
Samuli Lintunen
Leigh, I’m glad I could be of some help to you.
Big Thanks to Chris (and Phil) for providing the original work.
March 20, 2009 at 1:41 am
ASP.NET Hosting : Using ASP.NET MVC Routing to route the 404 Error Pages
[...] implementation (example created by Chris Cavanagh) // see http://chriscavanagh.wordpress.com/2008/03/11/aspnet-routing-goodbye-url-rewriting/ var startPageRouteHandler = new [...]
March 23, 2009 at 8:51 pm
Using ASP.NET MVC Routing to route the 404 Error Pages « ASPHostCentral - .NET3.5 Hosting & SQL Express Hosting
[...] // reference IRouteHandler implementation (example created by Chris Cavanagh) // see http://chriscavanagh.wordpress.com/2008/03/11/aspnet-routing-goodbye-url-rewriting/ var startPageRouteHandler = new [...]
March 30, 2009 at 2:49 am
Andy
I’m new to ASP.Net routing – is this technology reliant on IIS7? Having read different blogs and articles I’m getting conflicting information. I want something that will work on IIS 6.0 without having to install/configure anything within IIS.
Thanks in advance
Andy
March 30, 2009 at 8:24 am
Chris Cavanagh
Hi Andy – It’ll work in IIS6 but you do need to change a setting on your app in IIS that essentially sends *every* request to ASP.NET (even static content files). It’s called Wildcard Application Mapping and it’s mentioned a bit in this post:
http://chriscavanagh.wordpress.com/2008/04/25/systemwebrouting-with-webforms-sample/
Hope this helps!
April 10, 2009 at 10:42 am
Leigh
I’m finding that, when initially logging into the site, the CSS appears to be missing – The log in page has no style! After successfully logging in, everything is fine on subsequent log ins. Can anyone explain this, and how can I fix it?
Thanks
April 10, 2009 at 10:45 am
Chris Cavanagh
Leigh – I’ve seen this a few times with regular ASP.NET apps. Try adding some ‘location’ elements in your web.config to exclude your .css files from forms authentication. Do you get the same issue running under IIS, or just under VS/Cassini?
April 10, 2009 at 7:10 pm
Leigh
Thanks Chris. I think you might have hit the nail on the head there. I bet access to the CSS is being denied, due to my default settings. Thanks for the heads up! I’ll take a look…
April 15, 2009 at 5:34 pm
Evol
Has anyone experienced the following issue:
Could not load file or assembly ‘NameSpace’ or one of its dependencies. The system cannot find the file specified.
…
…
namespace NameSpace
{
///
/// Simple UrlRoutingHandler implementation
///
public class RoutingHandler : UrlRoutingHandler
{
protected override void VerifyAndProcessRequest( IHttpHandler httpHandler, HttpContextBase httpContext )
{
}
}
}
The class “UrlRoutingHandler” is as above and I have no problems running the site under VS08 or in IIS6.
April 16, 2009 at 11:51 am
Chris Cavanagh
Evol – Interesting error. Could you send me a sample project?
April 22, 2009 at 11:17 pm
localman
If anyone reads this post for prabhjot’s “The resource cannot be found.” error, make sure you double check your web.config matches the one in the example. Had the example running fine, but my app not. knew it had to be in there somewhere.
April 28, 2009 at 7:21 am
Leigh
Aargh! I’m unable to use cross page posting with routing. Attempting to use the PreviousPage property results in an HttpException, because the routed page doesn’t physically exist. Does anyone know of a way around this?
April 28, 2009 at 4:21 pm
Leigh
Ignore that – I worked around it.
I never did get a sitemap working with this stuff though. The MVC sitemap is simply too rigid for general routing (i.e. not using controllers and actions etc).
May 4, 2009 at 9:54 pm
Rod
Hi -
I am getting the same error as Evol (above): “Could not load file or assembly ‘SimpleRoutingTest’ or one of its dependencies.”
I used your VB sample with no alterations. It runs fine on my local machine, but not on my web server. The server is running IIS 7, .NET 3.5, but I obviously am overlooking a setting. Do you have any ideas?
May 10, 2009 at 10:03 am
priyanka
Hi Sir,
I need your help implementing breadcrumb or sitemap in asp.net routing website. Plz help me…….. as soon as possible……….
May 12, 2009 at 4:27 am
tso
how do I retrive parameter values from querystring when I use Routing
May 14, 2009 at 1:52 pm
Chris Cavanagh
tso – You can still use Request.QueryString[ "myparam" ] as usual. Let me know if I misunderstood your question!
May 15, 2009 at 4:49 am
Sandeep Aparajit
Hi Chris,
I had a query related to ASP.NET URL Routing functionality. At present even if the sitemap is not provided, the search engine crawlers crawl the website to find indexable pages. But with ASP.NET MVC patterns, we would have one single (controller) class serving multiple URL’s. Then is it made mandatory to provide an xml sitemap with the website? If not, then how will the search engine crawler be able to crawl our URL’s?
May 15, 2009 at 7:53 am
Chris Cavanagh
Sandeep – I’m not sure it would matter… I don’t know the rules the crawlers use, but I’d guess that as long as every possible page was linked from somewhere in your site you’d be ok (I’d also guess Googlebot etc allow you to identify your own search pages it can delegate requests to, or maybe not… need to ask an SEO expert
). As for the single controller serving multiple URLs, clients/spiders would never be aware of that (they’d only see public URLs we expose)… Lat me know if I misunderstood your question though and I’ll have a closer look!
May 18, 2009 at 9:31 pm
Sandeep Aparajit
Ya Chris, I agree to the fact that the spiders would never be aware of a single controller serving multiple URLs. I think the search engine spiders would be intelligent enough to search for public (exposed) URLs.
Thx!
May 19, 2009 at 10:36 pm
ASP.NET WebForm Routing with SiteMaps « Chris Cavanagh’s Blog
[...] 19, 2009 · No Comments I’ve updated my ASP.NET WebForm Routing demo with basic SiteMap support. It’s targeting ASP.NET 3.5 SP1 and expects your WebForm [...]
May 20, 2009 at 9:34 am
Chris Cavanagh
Leigh – If you still need some help with routing + SiteMaps, I’ve posted something that might help:
http://chriscavanagh.wordpress.com/2009/05/19/asp-net-webform-routing-with-sitemaps/
May 20, 2009 at 12:51 pm
Issa Qandil
Hello Chris,
I was wondering if you had any problem regarding postback with urls like this one :
[http]://[SomeDomain]/Cat/Product/ID/
If you looking into the generated page source you will notice that the form do a post with only the last action … i mean something will look like this:
Which will cause a server error due to the validation of the posted page … any ideas solving this.
Thanks,
I. Qandil
May 20, 2009 at 1:33 pm
Chris Cavanagh
Issa – I’d not seen this before (but have now, thanks!
). This seems to be the same issue:
http://stackoverflow.com/questions/230014/postback-not-working-with-asp-net-routing-validation-of-viewstate-mac-failed
I’ll dig into this some more and post an update…
May 20, 2009 at 1:55 pm
Chris Cavanagh
Issa – This looks like the same problem:
http://stackoverflow.com/questions/230014/postback-not-working-with-asp-net-routing-validation-of-viewstate-mac-failed
Unfortunately we need a hack to fix it
The main problem appears to be the s ‘action’ value is incorrect. A workaround is suggested here:
http://www.andreas-kraus.net/blog/404-error-while-using-aspnet-url-routing/
Until I find / figure out a better solution, I’ve added this to an OnLoad override in RoutablePage.cs:
Form.Action = HttpContext.Current.Request.RawUrl;
Hope this helps!
May 20, 2009 at 2:17 pm
Issa Qandil
Yep it is the same problem as in SO.
Your suggestion is great but shouldn’t that be placed in the page itself encase you need to do other things in OnLoad ?
Maybe putting it in another step in the PageLife Cycle
What do u think ?
May 20, 2009 at 2:28 pm
Chris Cavanagh
Issa – Here’s a better idea… Add some code into WebFormRouteHandler like this:
var webForm = page as Page;
if ( webForm != null ) webForm.Load += delegate { webForm.Form.Action = requestContext.HttpContext.Request.RawUrl; };
Same end result, but avoids polluting the page with an obvious hack
May 20, 2009 at 2:34 pm
Issa Qandil
And that’s what i call magic,
I was thinking of doing it from that place just before returning the page but i guess i was stuck
Thanks for you help i guess i will try it.
May 20, 2009 at 2:40 pm
Issa Qandil
And it did work perfectly … thanks
May 21, 2009 at 5:10 am
James Talbot
Hi, I’ve used routing for a bit now and have got it to work in a number of scenarios.
I’m now trying to see if I can get it to dissect the queryvalues of an originating url. i.e. if someone types http://www.mydomain.com/page.aspx?id=x then I want to reroute to a different page based on x.
I have the following line in global.asax.
Routes.Add(New Route(“page.aspx/{*pathInfo}”, New RouteHandler()))
However I can’t seem to get a value out for x in the RouteHandler.
I’ve tried accessing requestContext.RouteData.GetRequiredString(“pathInfo”) which is nothing.
and also tried going through the routedata.
Dim qs = New StringBuilder(“?”)
For Each aux In requestContext.RouteData.Values
qs.Append(HttpUtility.UrlEncode(aux.Key))
qs.Append(“=”)
If Not aux.Value Is Nothing Then qs.Append(HttpUtility.UrlEncode(aux.Value.ToString()))
qs.Append(“&”)
Next
qs.Remove(qs.Length – 1, 1)
Using this the key for pathInfo exists but the value is nothing…
Any ideas where I might be going wrong.
Thanks in advance.
May 21, 2009 at 5:31 am
James Talbot
Following on from my last post I decided to work with requestContext.HttpContext.Request.RawUrl which exposes the querystring values. Although this has solved my problem for the time being it would be good to know if I can go about it the other way.
May 21, 2009 at 12:50 pm
Chris Cavanagh
James – Since you’re just after the querystring parameters, could you just set your route as:
Routes.Add( New Route( “page.aspx”, new CustomRouteHandler(…) ) )
…then in your CustomRouteHandler implementation just grab requestContext.Request.QueryString( “x” ) and create the appropriate page …. ?
Your previous route with {*pathInfo} should do great capturing things like http://www.mydomain.com/page.aspx/my/sub/path (and will probably ignore querystring params).
Let me know if this helps (or if I misunderstood!
)
May 22, 2009 at 6:12 am
James Talbot
I’m sure that would do it yes. Thanks for the advice. I was too busy trying to break the routing module than consider using much simpler methods!
June 29, 2009 at 12:52 am
Sathish
Hi Chris,
I have implemented URL Routing in one of my project and it works fine. But i am not able to set the default page in my site. Suppose i enter “http://localhost/sitename/” it dosent take me to default.aspx page. Instead it gives me 404 error. Kindly help me out.
Thanks in advance
July 6, 2009 at 6:17 pm
Windows Web Hosting
This sounds really great. Routing removes the need of rewriting the URL. Thanks, will switch to this soon.
We are currently using Intelligencia.UrlRewriter component for rewriting, does this component need full trust asp.net level?
Thanks in advance.
July 6, 2009 at 9:28 pm
Chris Cavanagh
Marvin – The routing assemblies don’t need full trust. However, if you’re using IIS6 you’ll need to enable Wildcard Application Mapping (http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/5c5ae5e0-f4f9-44b0-a743-f4c3a5ff68ec.mspx?mfr=true) to send all requests through ASP.NET.
Hope this helps!
July 6, 2009 at 9:39 pm
Chris Cavanagh
Sathish – Are you using IIS 6, 7 or VS’s web server? You might need to define an additional fallback route to catch requests like that, or maybe tweak some IIS settings. See if this helps (can skim over dynamic data stuff): http://www.hanselman.com/blog/PlugInHybridsASPNETWebFormsAndASPMVCAndASPNETDynamicDataSideBySide.aspx
July 21, 2009 at 4:15 am
Kandaiya
Hi,
Is it possible to do URL routing to handlers like .ashx.
I got situation to redirect my requests to .ashx handler.
In simple, like Routes.Add(“/departments/accounts”,”depart.ashx”);
Thanks
July 21, 2009 at 4:44 am
Chris Cavanagh
Kandaiya – I’ve not tried it with handlers; I guess it just comes down to whether BuildManager.CreateInstanceFromVirtualPath can handle .ashx’s or not. I’ll try it out
(but let me know if you figure it out sooner!).
July 21, 2009 at 6:52 pm
How to build huge dynamic cross platform Silverlight Business Applications « An Original Idea
[...] Goodbye to Url Rewriting [...]
August 3, 2009 at 6:31 am
Leigh
Should output caching work with routing? I’m currently writing a web site that would benefit from caching, but it simply doesn’t seem to be working. I’m wondering if there are any known issues with routing and output/partial caching?
August 3, 2009 at 8:49 am
Chris Cavanagh
Hi Leigh – Good question; I don’t have a clue! If it’s not behaving as expected, it might be worth looking at what’s coming in ASP.NET 4 (or the latest futures stuff); might be something they’re addressing with the improved WebForms / routing support…
All I can suggest is get as many breakpoints in as you can; if all the requests are coming in as expected, I’d hope/expect it’d be relatively easy to diagnose. Let me know what you find (meanwhile I might kick it around in a test project).
August 4, 2009 at 3:41 am
Leigh
False alarm Chris. It does appear to be working as expected now.
Thanks again for this stuff – I use it in every one of my sites now.
August 26, 2009 at 3:15 am
Abhinav Agrawal
Hi chris
I am using free text box control on a .ascx file ie on a control file, on this there is a browse image option. On the page where routing is implemented and a control is used and in that control this free text control is used, because of why when we click browse image, wrong page gets open. This can not be changed as it is coming from a DLL
August 26, 2009 at 6:29 am
Chris Cavanagh
Abhinav – Have you contacted the textbox control authors? If it’s a bug in their control (likely if all your other content is working with routing) they could probably fix it pretty easily. Alternatively you could try opening the DLL in Reflector and use the FileDisassembler add-in (http://www.denisbauer.com/NETTools/FileDisassembler.aspx) to create a new source project, fix the bug yourself and rebuild the DLL
(relatively easy if it’s not been obfuscated). Hope this helps!
October 21, 2009 at 10:50 am
..:: Mãstän ::..
@Chris Cavanagh,
Nice article, Thanks for it.
I have small doubt, I tried lot find a solution, unable to get it. Its related to URL rewrite or URL mapping.
For example I have 2 folders in my asp.net project
1. good
2. bad
under this folder few aspx pages are there, whenever I access pages from this folder, in browser url it should shows that folder name only like calling http://localhost/good/page1.aspx” -> it need to show http://localhost/good, if I call page2.aspx or pageN.aspx in url it must show http://localhost/good, also same way in bad folder too.
For example, from good folder I’m calling page2.aspx normally its shows like /good/page2.aspx in address bar, if I call page1.aspx from good folder it also shows like /good/page1.aspx, other files also shows in that way. I want to hide page name, just want to show folder name like /good or /bad. If I follow url mapping or rewrite whichever you mention here … I cant fulfill my requirements.
how can I do this? could you help me pleaseeeeeeeeee??
I’m using ASP.NET 3.5
Thanks in advance.
Please help me this poor guy
–Mastan
October 21, 2009 at 11:35 am
Chris Cavanagh
Mastan – The Routing functionality should give you exactly what you want, but you’ll need to configure it appropriately. All it does is map a url pattern to a real WebForm (aspx). In this case you’d want to create a custom RouteHandler to determine which physical .aspx should handle the request.
Given that your required url includes the folder name, how do you intend to determine which .aspx to use? (ie, for http://localhost/good, should it hit ~/good/page1.aspx, ~/good/page2.aspx… etc).
November 13, 2009 at 12:43 am
Amit
Hi Chris,
can you please suggest me any way of routing in .net 2.0.I am rewriting URL for .html to .aspx pages.Since i don’t have access to IIS 6.0 to configure it to transfer .html request to aspnet_isapi.dll ISAPI extension, i can’t perform url rewriting for html pages.Is there any change i can do in web.config file or any other place to perform this.
Thanks
November 16, 2009 at 5:46 pm
Kasper
Hi Chris, great blog!
When I use your code in a WAP i get the same error as Evol and Rod:
“Could not load file or assembly ‘NameSpace’ or one of its dependencies”
Solution:
….
….
Netboss
November 16, 2009 at 5:52 pm
Kasper
hmm… where did my solution go?? I’ll try again
December 11, 2009 at 7:46 pm
Chris Cavanagh
Kasper – Did you get it figured out?
December 11, 2009 at 7:39 pm
Chris Cavanagh
Amit – Without having access to the server, and being restricted to ASP.NET 2.0, your options are limited
Could you send me some examples of the kind of URL’s you’re wanting to use?
December 26, 2009 at 7:20 pm
Dev Links « Blogosphere
[...] ASP.NET Routing… Goodbye URL rewriting? – Chris Cavanagh [...]
February 26, 2010 at 6:36 am
Mastan
Hi Chris,
Its really superb one.
Thanks for it. could you help me pls? does it possible to routing in subdomain? for example, http://sub.main.com/Test here sub and Test can change as per the user request. how can I do that?
thanks
February 26, 2010 at 6:39 am
Mastan
oppssss! sorry I didnt see ur response here…
( sorry sorry… again I’m facing problem in subdomain url rewrite
, seems I’m always stucking in URL rewritting
(… can u help me again pls?
February 26, 2010 at 2:51 pm
Chris Cavanagh
Mastan – Does this help?:
http://blog.maartenballiauw.be/post/2009/05/20/ASPNET-MVC-Domain-Routing.aspx
March 21, 2010 at 7:11 pm
Burak KARABABA
“The resource can not be found.” Solution to the problem (for IIS7):
March 21, 2010 at 7:13 pm
Burak KARABABA
March 21, 2010 at 9:41 pm
Chris Cavanagh
Burak – Sorry about WordPress comment editor
Which IIS 7 problem were you referring to?
June 13, 2010 at 11:51 pm
Gopakumar
Hi,
I implemented URL rounting partially, some of the page has routing and some dont. Now the problem i face is my forms authendication doesnt seems to work in URL routed pages but other pages it works.. When i see into my RouteHandler i can see that my context.user.identity is null. Where as in other page it has values. Basically i redirect to the routed page after authendication. Can you please let me know what could be the possible problem.. I use II7..
July 20, 2010 at 3:35 pm
[ASP.net] Home Access Plus+
[...] [...]
September 24, 2010 at 4:37 am
Pradeep
Hi,
I have a requirement related to subdomains. Here are the details.
I am using .NET 4.0, IIS7, ASP.NET 4.0. I have an web application hosted as “mycompany.com”. I have some clients, say client1, register at my site. I want to give him a
URL like http://client1.mycompany.com. Similarly for client2 URL will be http://client2.mycompany.com
http://mycompay.com has provision to allow new clients to register at my site. Any new client should able to view his area by using URL http://clientN.mycompany.com.
This is very similar to Microsoft’s spaces.live.com; Each individual having hotmail/live ID can access his spaces. Ex: http://ypradeep23.spaces.live.com
Can you please guide me in design this solution.
Regards,
Pradeep.
January 25, 2011 at 7:46 pm
Salvo
Crhis Hello, thanks for the article. I need to be replaced in VirtualPath me a parameter of the routing in WebFormRouteHandler. Example:
var mypage = new WebFormRouteHandler(“~/{page}.aspx”);
routes.Add(new System.Web.Routing.Route(“{language}/{page}.aspx”, mypage));
Thank you very much
February 9, 2011 at 2:27 pm
Haider
Visit this link for URL Routing in ASP.Net 3.5
http://www.mindstick.com/Articles/9992a0bc-90f5-4f04-823a-31f901b61643
May 12, 2011 at 12:57 am
vida
Hello,
I have a problem when I use Routing Method in my project.
I use .Netframework 4 and asp.net 2010.
I generated my project by Codesmith and .NetTiers template if you want i can send my sample project for your emai?
I read any topic about Url Routing but in my project it does not work,
I think IRouteHandler Dose not fire what should I do Please help me.
thanks vida .
May 14, 2011 at 1:38 am
ASP.NET URL Routing | Warren Tang's Blog
[...] Routing… Goodbye URL rewriting? http://chriscavanagh.wordpress.com/2008/03/11/aspnet-routing-goodbye-url-rewriting/ IIS URL Rewriting and ASP.NET routing [...]
July 6, 2011 at 11:02 pm
chamarairesh
Site Map Issue if URL contain “-m” automatically link will break
this my Sitemap node c
there -ma character is including.if -ma to chage any other charter than “m” link will work fine.
i have check this with working link and if i put -m for the working url link is breaking automaticaly.
July 6, 2011 at 11:04 pm
chamarairesh
Site Map Issue if URL contain “-m” automatically link will break
there -ma character is including.if -m to change any other charter than “m” link will work fine.
i have check this with working link and if i put -m for the working url link is breaking automatically.
November 12, 2011 at 10:27 am
A
add following in your web.config and it should work :
November 12, 2011 at 10:29 am
Apmnr
November 13, 2011 at 5:36 pm
How do I mix MVC views and ASPX pages inside the same folder? | trouble86.com
[...] This article, linked to from the one above, provides a handy class to help with your scenario. [...]
December 5, 2011 at 1:12 pm
ksen
i have custom http modules which is firing twice one for original request and the other for the router, Is any one know how to prevent this?
December 13, 2011 at 4:06 am
olum1989
Hi. I have used in asp.net 4 with this method :
routes.MapPageRoute(
“product”,
“Product/{ProductName}.mk”,
“~/product.aspx”
);
- but I have a problem
I have links like that : http://localhost:5327/Product/car-2.mk
when I click link , it becomes : http://localhost:5327/Product/Product/car-2.mk
– it repeats Product/
in product.aspx.cs I have only :
protected void Page_Load(object sender, EventArgs e)
{
string category = Page.RouteData.Values["ProductName"].ToString();
Label1.Text = “product – ” + category;
}
Can you help me , thanks …
January 20, 2012 at 12:58 am
smart class
very useful post thanks a tone…….
August 14, 2012 at 12:35 pm
Tech-Ed EMEA 08 II/II. rész – Fejlesztői szemmel - Csala Péter szakmai blogja
[...] http://chriscavanagh.wordpress.com/2008/03/11/aspnet-routing-goodbye-url-rewriting/ http://weblogs.asp.net/scottgu/archive/2007/12/03/asp-net-mvc-framework-part-2-url-routing.aspx [...]
January 24, 2013 at 12:58 am
khan
HI Chris,
I have implement url routing on my website project in vs 2010 and IIS 7.
But after impelemented I have facing issue where images and css some times load and some not.
please suggest ?
January 24, 2013 at 5:20 am
Chris Cavanagh
khan – Is there a pattern to when the images aren’t loaded? For example, do they only load after successful authentication, but fail before that? (you may need to hit CTRL+F5 to make sure the browser is requesting them each time, and not just caching). If you can tie it down to authentication, you might just need a element in your web.config, to exclude image (and probably css) files from forms authentication: http://msdn.microsoft.com/en-us/library/b6x6shw7(v=vs.71).aspx
January 24, 2013 at 5:26 am
khan
HI Chris,
Thanks for your quick response.
I don’t know about any pattern but have facing this type of issue after placed url routing.
Some times Images are displayed and some times not.
I really stuck last 3 days and haven’t found any solution.
January 24, 2013 at 5:28 am
khan
Also images are in server folder but still it’s displayed cros in IE or any browser.
It’s happen randomly.
January 24, 2013 at 5:36 am
Chris Cavanagh
khan – Try using the debugger in your browser… Most current browsers can show a “resources” list that includes all images, css files etc… If there’s an error retrieving one of them, it’ll usually tell you about it.
How large are the images?
January 24, 2013 at 5:41 am
khan
Hi Chris,
It’s happen for whole the website not matter image is 2 kb or larger.
Some time website are totally distorted because it’s not loading any css or js.
when I refresh or browse site page by page, It’s displayed fine but again after few minutes images are not displayed.
January 24, 2013 at 5:45 am
Chris Cavanagh
khan – Something pretty weird going on there… Is it using IIS and running on your local machine, or deployed on a public server / host? If this is using the Visual Studio dev host (Cassine, IIS Express etc), does the same thing happen if you run in IIS and / or publish live?
January 24, 2013 at 6:16 am
fahim khan
Hi Chris,
I have attached two screen shot.
First one image is not displayed on the page and second when I have used direct url for that image it’s showing fine.
Regards,
Khan
On Thu, Jan 24, 2013 at 11:45 AM, Chris Cavanagh’s Blog wrote:
> ** > Chris Cavanagh commented: “khan – Something pretty weird going on > there… Is it using IIS and running on your local machine, or deployed on > a public server / host? If this is using the Visual Studio dev host > (Cassine, IIS Express etc), does the same thing happen if you run in II” >
January 24, 2013 at 5:47 am
khan
I am using IIS 7.
January 24, 2013 at 8:06 am
Chris Cavanagh
Any luck using your browser’s debugger / web inspector?
January 24, 2013 at 8:36 am
khan
No, still facing same issue.
I am working 4-5 website but this issue occur on those website where I placed routing.
January 24, 2013 at 8:45 am
Chris Cavanagh
khan – Best guess is the routing is picking up the image requests and trying to map them to an action… Doesn’t explain the randomness, unless the browser is choosing to pull previously cached versions on the occasions it “works” (and with direct url). You might find some hints here:
http://www.phpvs.net/2009/08/06/aspnet-mvc-how-to-route-to-images-or-other-file-types/
Alternatively, you could create an action specifically to serve your images and resources. It’s a bit heavier than just letting IIS handle it, but could give you more control (for instance serving smaller versions of existing images):
http://dotnetslackers.com/articles/aspnet/ASP-NET-MVC-3-Controller-for-Serving-Images.aspx
January 24, 2013 at 8:59 am
khan
Chris,
I have checked above url but it all about in MVC.
I have created simple CMS and place dynamic url routing using global.asax file and all images with content comes from database.
I have checked images are not very large in size.
Could you please check the below link for me -
http://www.indexksa.com
January 24, 2013 at 9:40 am
Chris Cavanagh
khan – How are the images pulled from the database? Do you have an HttpHandler or something, and is it possible to add some logging in there?
January 24, 2013 at 9:49 am
khan
Hi Chris,
Images is in the html content.
It’s simply through sql query I am not using any handler. The saved content in database like below –
As Media Partners, every one of the below publications has committed to supporting INDEX KSA in full. They dedicate sections of their news pages, schedule special features around the exhibition and can provide exhibitors with valuable additional support helping make the most of their participation.
ITP
Commercial Interior Design is an invaluable source
of ideas, inspiration and product information for industry professionals across the Middle East. Commercial Interior Design has a BPA audited circulation of 6034 and has quickly become the must-read publication for industry professionals in the Middle East.
Commercial Interior Design covers all aspects of commercial interiors, from residential to industrial, offices to warehouses, hotels to health spas and everything in between.
Commercial Interior Design is part of the construction and design stable of titles published by ITP Business – Publisher of more trade titles than any company in the Middle East.
For your free one year subscription to Commercial Interior Design please log on to http://www.itp.com/subscriptions
January 24, 2013 at 10:08 am
Chris Cavanagh
khan – I’m curious how the SQL query is executed… Is that part of your site? Trying to understand how the routing could be getting involved…
January 24, 2013 at 10:19 am
fahim khan
Hi Chris,
I have attached some page and global.asax file.
I have saved route for all page in database and fetch route from database through global.asax (application beginrequest) and add in route file and use route classes.
Please see attached file.
On Thu, Jan 24, 2013 at 4:11 PM, Chris Cavanagh’s Blog wrote:
> ** > Chris Cavanagh commented: “khan – I’m curious how the SQL query is > executed… Is that part of your site? Trying to understand how the routing > could be getting involved…” >
February 6, 2013 at 2:56 am
Fahim Khan
HI Chris,
Thanks for your help.
I have found solution.
I have added *System.Web.Routing.RouteTable.Routes.RouteExistingFiles = false; *in my global.asax file and it’s working fine now.
Regards,
Fahim
January 24, 2013 at 10:36 am
khan
Hi Chris,
Thanks for your response.
Please if you will find any solution then respond me.
Now I am leaving for the day because I am in india and now here 10:15 PM.
Thanks,
Khan
January 24, 2013 at 11:21 am
Chris Cavanagh
Khan – You can send files to me at blog_khan@chriscavanagh.com (if you’re replying here via email, attachments are ignored).