I am new to asp.net mvc and now struggling with url routing. I'm using asp.net mvc 3 RC2.
How can I create a url routing that IGNORES the very end extension in url. the extension can be: .html
, .aspx
, .php
, .anything
.
For example, these urls:
/Home.html
/Home.en
/Home.fr
/Home
should go to Home
controller?
one more example:
/Home/About.html
/Home/About.en
/Home/About.fr
/Home/About
should go to Home
controller and About
action.
thank you :)
If you are using IIS 7, you should look at Dan Atkinson's answer.
I'm using IIS 6, so, in my case, I have the option to install isapi rewrite for IIS 6 or create custom route. I prefer to create my simple custom route class
AndraRoute.cs
RouteCollectionExtensionHelper.cs
RegisterRoutes method in Global.asax
You could handle this in IIS instead of ASP.NET MVC using IIS Url rewriting. See for example: http://learn.iis.net/page.aspx/496/iis-url-rewriting-and-aspnet-routing/
Using the
Application_BeginRequest
, will allow you to intercept all incoming requests, and allow you to trim the extension. Make sure to ignore requests for your content, such as .css, .js, .jpg, etc. Otherwise those requests will have their extensions trimmed as well.I started to work on this question as a weekend assignment :D
below code will work as requested in question. please refer below references
1] MyUrlRoute Class : RouteBase
}
in global.asax.cs add below code
working as expected.
possibly you can improve if/elseif code.
I'm not sure if you're using IIS7, but if so, then I would recommend a rewrite rule which checks for urls ending in
.xyz
and then doing a rewrites for them without the.xyz
.Something like this:
This will handle the use cases you suggested. Anything that ends with an extension and some characters will be rewritten to a url without the extension. The benefit of this is that you will only need one route because everything goes into your application without one.
You just need to tweak the default route in Global.asax.cs, try this:
The {extension} value from the url will be included in the route data, but you can just safely ignore it if you don't need it