You are on page 1of 17

UrlRewritingNet.

UrlRewrite
Documentation
AlbertWeinert&ThomasBandt

2.0

WWW.URLREWRITING.NET

Tableofcontents
WhatisUrlRewritingNet.UrlRewrite?..........................................................................................................4
WhyrewritingmyUrls?...........................................................................................................................4
FunctionsofUrlRewritingNet.UrlRewrite................................................................................................4
LimitationsofUrlRewritingNet.UrlRewrite..............................................................................................4
Notablethingsbydevelopingawebapplication.........................................................................................6
Makeyourrewriterulessospecificaspossible......................................................................................6
Usetherootoperator~........................................................................................................................6
WorkingwithUrlswithoutfileextension................................................................................................6
DifferencesbetweenIISandVisualStudioWebDevServer....................................................................6
InstallationofUrlRewritingNet.UrlRewrite.................................................................................................7
Systemrequirements...............................................................................................................................7
Installation...............................................................................................................................................7
InstallationoftheAssembly.................................................................................................................7
Installationoftheconfigurationschema.............................................................................................7
SettinguptheconfigurationsettingsareaintheWeb.config.............................................................7
EmbeddingUrlRewritingNetasHttpModul.........................................................................................8
Necessarychangesbyupgradingfrom1.1to2.0....................................................................................8
Giveyourrulesuniquenames.............................................................................................................8
RemovecompileRegExattribute......................................................................................................8
Refreshconfigurationschema.............................................................................................................8
Configuration...............................................................................................................................................9
Attributesfor<urlrewritingnet/>............................................................................................................9
The<providers/>listing.......................................................................................................................10
The<rewrites/>listing..........................................................................................................................10
RegExRewriteAttributes.......................................................................................................................11
Settingsonthewebserver(IIS)..................................................................................................................12
AssignotherfileextensionswithASP.NET2.0.......................................................................................12
IIS5.0/5.1...........................................................................................................................................12
IIS6.0..................................................................................................................................................12
HandleallrequestsbyASP.NET2.0.......................................................................................................12
IIS5.0/5.1...........................................................................................................................................12
IIS6.0..................................................................................................................................................12
ChangingofRewriteRulesonruntime......................................................................................................13
CreateyourownRewriteRuleProvider....................................................................................................14
Developingtherewritelogic..................................................................................................................14
Creationofanewprovider....................................................................................................................16
EmbeddingtheproviderinWeb.config.................................................................................................16
Copyrightnotice.........................................................................................................................................17

www.urlrewriting.net

Page2

www.urlrewriting.net

Page3

WhatisUrlRewritingNet.UrlRewrite?
UrlRewritingNet.UrlRewriteisamodulewhichcouldbeembeddedinanASP.NET2.0applicationto
rewriteUrls(Internetaddresses)fordisplayingtheuseranotherURLthanusedfromtheserver.With
UrlRewritingNet.UrlRewriteyouonlyhavetodefineafewsimplerulesforrewritingyouraddresses.

WhyrewritingmyUrls?
Alittleexample.Youredevelopingblogsoftwarewhichstoresitsentriesinadatabase.Togettheentry
fordisplayingitinadetailspageyouneedtheidentity(ID)oftherecordtodisplay.TogettheIDyou
usuallytransportthisvaluebyQueryString:http://myblog.com/details.aspx?id=234.
IfyourblogisreadyandonlineyouwanttobefoundbypotentialreadersonsearchengineslikeGoogle
orYahoo.ThesesearchenginessendbotsouttotheWorldWideWebtofindinterestingcontent.So
whatdoyoumeanwhatthebotdoeswithaUrllikeshownabove?Notmuch,right.
So,wouldntitbecoolerifthebotcouldfindthetopicoftheblogentryintheUrlforexample?A
rewrittenUrlcouldlooklikethis:http://myblog.com/detail/goodnewsforabetterworld234.aspx.
Themachine(searchenginebot)hassomethingtoanalyzeandtheusercanimaginewhatthetopicis
aboutonthispage,too.

FunctionsofUrlRewritingNet.UrlRewrite
TherearesomesolutionsforrewritingUrlswithASP.NET,butmostlytherearesomedisadvantages,for
examplemissingsupportforThemesandMasterPages.ForsomeyouneedAdministratorrightsto
installanISAPIextensionontheserver.
ThisisntnecessarybyUrlRewritingNet.UrlRewriteandyoucouldavoidmanyproblems.

RewritingUrlsbasedonregularexpressions
SupportforThemesandMasterPages
SupportforOutputCacheing
Useinmediumtrustlevelenvironments(sharedhosting)possible
ConsistentUrlafterpostback
Addingownrewriteruleproviderspossible
Redirects(alsopermanent)tootherdomainsorwebsitespossible
SupportforCookielessSessions
Addingrewriterulesonruntime
Veryeasyinstallationanduse

LimitationsofUrlRewritingNet.UrlRewrite
Somanygoodthingshaveofcourseashadyside,too.Becauseofrewritingwiththe.NET2.0engine
onlyrequestscomingoverASP.NET2.0canbehandled.Thismeansthatthefileextensionhavetobe
handledbyASP.NET2.0ISAPIlibrary(see:ServerSettings,page14).Bydefaultthisisforexample.aspx
butifyouwanttorewritewithotherextensions,youhavetosetthisupbyyourselforaskyour
Administratortodothis.

www.urlrewriting.net

Page4

Forthisreasonthereisalsonorewritewithoutextensionpossible(forexample
http://myblog.com/user/bill).Forasolutionforthisspecialproblemseepage6,RewriteUrlswithout
fileextension.
Wearealsosorrytotellyou,thatCrossPagePostingsarenotavailableyetwithoutdisablingsecurity
checks.

www.urlrewriting.net

Page5

Notablethingsbydevelopingawebapplication
Forfastsuccessyoushouldtakealookatthefollowingbasics.

Makeyourrewriterulessospecificaspossible
Ifyoumakeyourrulesnotspecificenough,youwillgeneratenotexpectedeffects.Forexampleyou
avoidaccessonimages,stylesheets,webservices,javascriptsorotherelementsontheserver.
Sopleasespecifyyourrulesasexactlyaspossible.Forexamplenot^~/(.*)/(.*).aspx.Usethespecific
regularexpressionelementsfornumbersifyouawaitnumbersandnogenericplaceholderandsoon.

Usetherootoperator~
Foraccessonresourcesinyourweb(forexampleimages,stylesheetsorjavascripts)alwaysusethe
rootoperator~.Withthisoperatoreverypathwillbuildcorrectly,startingfromtheapplicationsroot.
Right <asp:ImageImageUrl=~/images/pictures.gifrunat=server/>
Wrong<asp:ImageImageUrl=../../images/pictures.gifrunat=server/>

YoucanalsousethisforHtmlControls.Justaddrunat=serveranditworks.
<imagesrc=~/images/pictures.gifrunat=server/>.
Iftheheadtagisrunningonserver(runat=server)youcanleaveouttherunatattributeherefor
JavaScriptandstylesheettags(andonlyhere,notinthebodyofthedocument!).

WorkingwithUrlswithoutfileextension
IfyouwanttoworkwithUrlswithoutfileextensionyoufirsthavetoconfiguretheIIS(seepage14,
settingsonserver)
NowyouhavedefinedadefaultPageintheUrlrewritingNetconfigurationsectioninWeb.config.With
thatsettingrequestson/folder/areredirectedto/folder/default.aspx,iftheattributeissetto
default.aspxforexample.
ThisisnecessarybecauseotherwiseASP.NET2.0couldntresolvetherightaddressbycalling
ResolveClientUrl()method,whichbringssomefunnyeffectswithThemesforexamplewith.
Important:therewriterulehastobeconfiguredtohandlethedefault.aspxandnottheUrlwithout
extension!

DifferencesbetweenIISandVisualStudioWebDevServer
UrlRewritingNetisworkingwithIIS(InternetInformationServices)aswellwiththeVisualStudio2005
builtinwebserver.Butthereisalittledifference.
TheWebDevServerpassesevery(!)requestthroughASP.NETIISdont.
Thisisimportantifyouwanttouseextensionslike.html,.php,xmlorotherforexample,orifyoure
workingwithoutfileextensions.Thebuiltinserverdoeshandlethiscorrectly,theIIShastobesetup
beforegettingthisrunningonit.InouropinionthebestwaytotestistousetheIISalsoonthe
developmentmachine.

www.urlrewriting.net

Page6

InstallationofUrlRewritingNet.UrlRewrite
Systemrequirements
UrlRewritingNet.UrlRewriteisrunningoneachWebserverwhichisrunningASP.NET2.0.
TestedWebserverwithUrlRewritingNet.UrlRewrite:

IIS5.0
IIS5.1
IIS6.0
VisualStudio2005WebDevServer

WedidnttestitwithMono.

Installation
ToinstallUrlRewritingNet.UrlRewriteyouhavetofollowtheseeasysteps:
1.
2.
3.
4.

InstallationoftheAssembly(.dll)
Installationoftheconfigurationschema
SettinguptheconfigurationsettingsareaintheWeb.config
EmbeddingUrlRewritingNetasHttpModule

InstallationoftheAssembly
JustcopyUrlRewritingNet.UrlRewriter.dllinyourwebapplications/binfolder.
Installationoftheconfigurationschema
TogetIntelliSensesupportjustcopythefileurlwritingnet.xsdinyouwebapplication(whereveryou
want).Ifyouwebapplicationispartofasolution,youcanalsoputthefileanywhereinthesolution.
SettinguptheconfigurationsettingsareaintheWeb.config
Togettheconfigurationsettingsfromtheweb.configthisareahastobeadvertised.Justreplacethe
<configSections>ifexists.
<configuration>
<configSections>
<sectionname="urlrewritingnet"
restartOnExternalChanges="true"
requirePermission="false"
type="UrlRewritingNet.Configuration.UrlRewriteSection,
UrlRewritingNet.UrlRewriter"/>
</configSections>
</configuration>

Iftheareaisadvertised,justcreateit.
<urlrewritingnet
xmlns="http://www.urlrewriting.net/schemas/config/2006/07">
</urlrewritingnet>

Thissectionhastobeplacedin<configuration/>butafter<configSections/>.Donotplacethisin
<appSettings/>or<system.web>!Foexamplesethesamplewebapplication.TogetIntelliSense
supportyouhavetoaddthexmlnsattribute.

www.urlrewriting.net

Page7

EmbeddingUrlRewritingNetasHttpModul
TohandleallincomingrequestswithUrlRewritingNetyouhavetoregisterthecomponentasHttp
Moduleinthe<system.web/>sectioninWeb.config.
<system.web>
<httpModules>
<addname="UrlRewriteModule"
type="UrlRewritingNet.Web.UrlRewriteModule,UrlRewritingNet.UrlRewriter"/>
</httpModules>
</system.web>

NowUrlRewritingNetconfigurationiscomplete.

Necessarychangesbyupgradingfrom1.1to2.0
Byupgradingfrom1.1to2.0youhavetochangealittlebitonyourexistingconfiguration.
1. Allrulesneedauniquename.
2. DontusetheattributecompileRegExanymore.
3. Refreshconfigurationschema
Ifoneoftheserequirementsisnotgiven,theapplicationthrowsexceptions.
Giveyourrulesuniquenames
Allexisting(andofcoursenew)ruleshavetogetuniquenames.Thisisnecessarytochangethemon
runtime.
Oldruleentry:
<addvirtualUrl="^~/girls/(.*)/(.*).aspx"
rewriteUrlParameter="ExcludeFromClientQueryString"
destinationUrl="~/Default.aspx?name=$1&amp;show=$2"
ignoreCase="true"/>

Newruleentry:
<addname="Gallery"
virtualUrl="^~/girls/(.*)/(.*).aspx"
rewriteUrlParameter="ExcludeFromClientQueryString"
destinationUrl="~/Default.aspx?name=$1&amp;show=$2"
ignoreCase="true"/>

RemovecompileRegExattribute
TheattributecompileRegExhasbecomeobsolete.Sopleaseremoveitfromallentriesandthe
<urlrewritingnet/>configurationarea.
Refreshconfigurationschema
ForgettingIntelliSensesupportyouhavetoupdatethenamespacetothecurrentversion.
<urlrewritingnet
xmlns="http://www.urlrewriting.net/schemas/config/2006/07">

Andofcourseyouhavetoreplacetheexistingurlrewritingnet.xsdwiththenewone.

www.urlrewriting.net

Page8

Configuration
vonUrlRewritingNet.UrlRewriteisconfiguredintheareainWeb.configwhichyousetupduringthe
installation(seepage8).
Herealittlesample:
<urlrewritingnet
rewriteOnlyVirtualUrls="true"
contextItemsPrefix="QueryString"
defaultPage="default.aspx"
xmlns="http://www.urlrewriting.net/schemas/config/2006/07">
<providers>
<addname="MyGreatProvider"type="MyApp.Web.MyGreatProvider,
MyGreatProvider.dll"/>
</providers>
<rewrites>
<addname="Rule1"virtualUrl="^~/(.*)/Detail(.*).aspx"
rewriteUrlParameter="ExcludeFromClientQueryString"
destinationUrl="~/Default.aspx?language=$1&amp;id=$2"
ignoreCase="true"/>
<addname="Rule2"
provider="MyGreatProvider"
myattribute="/foo/bar/dhin.aspx"
rewriteUrlParameter="ExcludeFromClientQueryString"
rewrite="Domain"
ignoreCase="true"/>
</rewrites>
</urlrewritingnet>

Thisconfigurationcanbecomeverycomprehensive,soyoucanswapitoutintoanexternalconfigfile.
PleaseusetheconfigSourceattributeforthat:
<urlrewritingnetconfigSource="ExternalRewrite.config"/>

InExternalRewrite.configyouhavetoputthecompleteconfigurationarea.

Attributesfor<urlrewritingnet/>

rewriteOnlyVirtualUrls
true,false(Standard:true)
Preventsrewritingforrealexistingfilesontheserveriftrue.
contextItemsPrefix
String
IftheQueryStringparametersshouldputteddowninHttpContext.Current.Items[],you
candefineaprefix,whichwillbeinsertedbeforetheparametersnamewithapoint
after.
defaultProvider
ProviderName(Standard:RegEx)
NameofthedefaultRewriteProviderusedifnootherisassigned.

www.urlrewriting.net

Page9

defaultPage
Dateiname
Nameofthedefaultpagewhichisusedonaccesswithoutfileextension(seepage6,
workingwithoutfileextension).

The<providers/>listing
Herecanthecustomprovidersbeadded.Foremoreinformationseepage19Embeddingtheprovider
intheWeb.configandthedocumentationofthespecificprovider.

The<rewrites/>listing
Herecantherewriterulesbeadded.Therulesareprocessedfromuptodown,thefirstmatchingruleis
usedfortherewritingandtheprocessisbeingready(nomorerulewillbeprocessed).
Toaddanewrulejusttypeanew<add/>element,IntelliSensewillpresentyoutheavailableattributes
whicharelistedbelow.
name
Nameoftherule
Afreeselectablenameoftherulewhichhastobeunique.Withthisname(ID)youcan
dosomemagicwiththisruleprogrammatically,too(seepage16)
provider
ProviderName
Nameoftheusedprovider.Ifnooneisselected,thedefaultproviderwillbeused.
redirect
None,Application,Domain(Standard:None)
Tomakearedirectinsteadofarewrite.
None
Normalrewrite
Application Redirectwithinyourwebapplication
Domain
RedirecttoanotherdomainwhichhastobepartofthedestinationUrl
redirectMode
Permanent,Temporary(Standard:Temporary)
Hereyoucanselectofwhichtypeyourredirectispermanent(HTTPstatuscode301)
ortemporary(HTTPstatuscode302).Ifyouwanttotransferawebsitefromone
domaintoanotherpermanentlyusePermanent.
rewrite
Application,Domain(Standard:Application)
Defineswhetherthedomainhastobeincludedintheprocessornot.
rewriteUrlParameter
ExcludeFromClientQueryString,StoreInContextItems,IncludeQueryStringForRewrite
(Standard:ExcludeFromClientQueryString)

ExluceFromClientQueryString
InRequest.QueryString[]allparametersareavailable.InPage.ClientQueryStringareonly

www.urlrewriting.net

Page10

theparametersadded,whicharevisibleinthebrowsersaddressfield,soapostbackis
possible.ParametersaddedindestinationUrlarenotaddedinPage.ClientQueryString.

StoreInContextItems
AllparameterslistedintheUrlfieldofthebrowserandtheparametersfromtherewrite
areaddedinHttpContext.Current.Items[]too,prefixedbyastringdefinedin
contextItemsPrefix.

IncludeQueryStringForRewrite
IncludethefullQueryString(theparametersinthebrowsersaddressfield)inthe
rewriteprocess,sothattheycanbehandledbytheengine.

Asadeveloperofarewriteprovideryoushouldlooktodevelopyourprovidermeetingthestandard
behavior,butofcourseitcanvary.

RegExRewriteAttributes
Ourstandardproviderhasthefollowingattributes.
virtualUrl
regularexpression
AregularexpressionwhichisusedforreplacingthecurrentUrlwithdestinationUrl.
destinationUrl
regularexpressionreplacementterm
Aregularexpressiontermdescribingthetargetpage(physicalfile).
regexOptions
Multiline,ExplicitCapture,Singleline,IgnorePatternWhitespace,RightToLeft,
ECMAScript,CultureInvariant
Foranoptimalcontrolovertheregularexpressionsyoucanaddadditionalto
ignoreCaseheresomeRegexOptions.Butthisisonlynecessaryinspecialcases.For
moreinformationseetheMicrosoftMSDNdocumentation.

www.urlrewriting.net

Page11

Settingsonthewebserver(IIS)
NormallyUrlRewritingNet.UrlRewritewillworkwithoutanyadministrativesettingsonIIS.Butifyou
wantsomeadditionalfeaturelikemappingspecificfileextensionstohandlethemwithASP.NET(for
example.xmlor.html),youhavetodosomethingonthewebserver.
Werecommenddoingthisonlyifyouknowwhatyouaredoing.Remember:neverchangearunning
system!

AssignotherfileextensionswithASP.NET2.0
IIS5.0/5.1
IIS6.0
OpentheIISManagertool,selectthewebwhichyouwanttoconfigureandopenthesettingsmenu.
SelectregisterHomeDirectory,gotoApplicationsettingsandclickonConfiguration.
HereyoucanaddadditionalfileextensionsormapexistingextensionstoASP.NETunderregister
Mappingswiththefollowingsettings.
Executable
c:\windows\microsoft.net\framework\v2.0.50727\aspnet_isapi.dll
(canvarybyinstallation)
Extension
.html
(Samplefor.html)
Verbs,Limitto)
GET,HEAD,POST,DEBUG
Scriptengine
check
Verifythatfileexist
checkoff

HandleallrequestsbyASP.NET2.0
IIS5.0/5.1
Handleallrequestswithplaceholder*.*byaspnet_isapi.dll.
IIS6.0
WithIIS6youcanthandle*.*requests,butyoucanassignanISAPIfilterasanapplicationplaceholder
(Wildcardapplicationmaps).Forityouhavetofollowthestepsdescribedonpage14,butnotaddinga
fileextensionunderWildcardapplicationmaps,but
c:\windows\microsoft.net\framework\v2.0.50727\aspnet_isapi.dll.
Donotcheckverifythatfileexists!

www.urlrewriting.net

Page12

ChangingofRewriteRulesonruntime
ForchangingtherewriterulesonruntimeUrlRewritingNet.UrlRewriteoffersfourstaticmethods:
namespaceUrlRewritingNet.Web
{
staticpublicclassUrlRewriting
{
publicstaticvoidAddRewriteRule(stringruleName,
RewriteRulerewriteRule);

publicstaticvoidRemoveRewriteRule(stringruleName);

publicstaticvoidReplaceRewriteRule(stringruleName,
RewriteRulerewriteRule);

publicstaticvoidInsertRewriteRule(stringpositionRuleName,
stringruleName,
RewriteRulerewriteRule);
}
}

Theparametersareverysimilar,ruleNameisthenameofthecurrentruleandrewriteRulethecurrent
ruleobject.
WithAddRewriteRule()newrulescanbeadded(attheendofthelist)andwithRemoveRewriteRule()
rulescanberemoved,withReplaceRewriteRulesurpriserulescanbereplacedandwith
InsertRewriteRule()arulecanbeaddedonadefinedposition.
IthasalwaysanewinstanceoftheRewriteRuleclasstobecreatedwiththewantedparameters.Isa
rulechangingitisavailableduringtheruntimeoftheapplicationiftheapplicationisbeingrestarted,
alsoallchangeshavetobedoneagain.
Herealittlesample:
RegExRewriteRulerule=newRegExRewriteRule();
rule.VirtualUrl="^~/abteilung/(.*)/default.aspx";
rule.DestinationUrl="~/showabteilung.aspx?abteilgun=$1";
rule.IgnoreCase=true;
rule.Rewrite=RewriteOption.Application;
rule.Redirect=RedirectOption.None;
rule.RewriteUrlParameter=RewriteUrlParameterOption.ExcludeFromClientQueryString;
UrlRewriting.AddRewriteRule("AbteilungsRegel",rule);

UrlRewriting.RemoveRewriteRule("AbteilungsRegel");

www.urlrewriting.net

Page13

CreateyourownRewriteRuleProvider
IfyourelimitedbythewaytheLibraryusuallywithRegularExpressionsworks,itispossibletodevelop
andintegrateanownRewriteRuleProvider.
Thedevelopmentcanbedividedin3steps:
1. Developingoftherewritelogic
2. Creationoftheprovider
3. EmbeddingtheproviderinWeb.config
Thatsit.YoudonthavetoconcernaboutThemes,Cachingandsoonthisdoes
UrlRewritingNet.UrlRewriteanymore.
AssampleimplementationweproviderthebuiltinRegExProvider.

Developingtherewritelogic
Youareabsolutelyfreeinimplementingyourownlogicwithanownprovider.Youonlyhavetoconsider
somelittlerules.
TheclassimplementingyourlogichastobebasedoftheabstractclassRewriteRule.Andithasto
override3methods:Initialize(),IsRewrite()andRewriteUrl().
IfasuitableRewriteRuleisaddedintheconfigurationanobjectoftheclasswillbeinstantiatedbythe
provider(onceperruntime).Youhavetoconsiderthatwebapplicationsaremultithreaded,soyouhave
tosynchronizeyourdatabyyourselfinsideoftheobjectbecausepossibleconcurrentcallsofthe
methods.Youshoulddevelopthesemethodsastheywerestaticmethods.
publicoverridevoidInitialize(RewriteSettingsrewriteSettings);

Onetimecalledbyinstantiatingtheclass.HereyoushouldreadouttheRewriteSettings.Theclass
RewriteSettingsoffershelpermethodsfordoingthis.
publicoverrideboolIsRewrite(stringrequestUrl);

HereyoushouldshortlytestiftheURLpassesintoyourrewriteschema(returntrue;)ornot(return
false;),nothingmoreifpossible.
publicoverridestringRewriteUrl(stringUrl)

HereyouhavetoimplementthemagicwhichmakesthephysicalUrlfromthevirtualone.Asreturn
valueitawaitstherealaddress.Considerwhetheritwasadomainrewriteoranapplicationredirect
orrewrite.

www.urlrewriting.net

Page14

AsampleimplementationofRegExRewriteRule.
publicclassRegExRewriteRule:RewriteRule
{
privateRegexregex;
publicoverridevoidInitialize(RewriteSettingsrewriteSettings)
{
base.Initialize(rewriteSettings);
this.RegexOptions=rewriteSettings.GetEnumAttribute<RegexOptions>("regexOptions",
RegexOptions.None);
this.VirtualUrl=rewriteSettings.GetAttribute("virtualUrl","");
this.destinationUrl=rewriteSettings.GetAttribute("destinationUrl","");
}
privatevoidCreateRegEx()
{
UrlHelperurlHelper=newUrlHelper();
if(IgnoreCase)
{
this.regex=newRegex(urlHelper.HandleRootOperator(virtualUrl),
RegexOptions.IgnoreCase|RegexOptions.Compiled|regexOptions);
}
else
{
this.regex=newRegex(urlHelper.HandleRootOperator(virtualUrl),
RegexOptions.Compiled|regexOptions);
}
}
privatestringvirtualUrl=string.Empty;
publicstringVirtualUrl
{
get{returnvirtualUrl;}
set
{
virtualUrl=value;
CreateRegEx();
}
}
privatestringdestinationUrl=string.Empty;
publicstringDestinationUrl
{
get{returndestinationUrl;}
set{destinationUrl=value;}
}
privateRegexOptionsregexOptions=RegexOptions.None;
publicRegexOptionsRegexOptions
{
get{returnregexOptions;}
set
{
regexOptions=value;
CreateRegEx();
}
}
publicoverrideboolIsRewrite(stringrequestUrl)
{
returnthis.regex.IsMatch(requestUrl);
}
publicoverridestringRewriteUrl(stringurl)
{
returnthis.regex.Replace(url,this.destinationUrl,1);
}
}

www.urlrewriting.net

Page15

Creationofanewprovider
TheonlyjoboftheprovideristoinstantiateanobjectofyourownRewriteRuleclass.Additionallogic
isntnecessary.
YourownproviderhastobebasedonclassUrlRewritingRuleProviderandhastoimplementonlyone
method.
Hereacompleteclass:
publicclassRegExUrlRewritingProvider:UrlRewritingProvider
{
publicoverrideUrlRewritingNet.Web.RewriteRuleCreateRewriteRule()
{
returnnewRegExRewriteRule();
}
}

Thatsit!
Ofcourseyoucantriggermoreparameterstotheproviderifyouneedmore,likeineveryother
ASP.NET2.0providerbyoverridetheInitialize()method.

EmbeddingtheproviderinWeb.config
ForworkingwiththenewprovideryouhavetoregisteritinWeb.config.Simplycreateaproviderslist
afterASP.NET2.0providerstandardschema.
<providers>
<addname="MyProviderName"type="Classname,Assembly"/>
</providers>

Youcanaddmultipleproviders.Bygivingyourprovideranameyoucanassigneachruletoitsprovider.
BydefaultthestandardproviderisRegExunlessyouaddonewiththisname.Asampleconfiguration:
<urlrewritingnet
rewriteOnlyVirtualUrls="true"
contextItemsPrefix="QueryString"
defaultProvider="RegEx"
defaultPage="default.aspx"
xmlns="http://www.urlrewriting.net/schemas/config/2006/07">
<providers>
<addname="MyProviderName"type="MyProviderClassname,MyAssembly"/>
</providers>
<rewrites>
<addname="Rule1"
provider="RegEx"
virtualUrl="^~/girls/(.*)/(.*).aspx"
rewriteUrlParameter="ExcludeFromClientQueryString"
destinationUrl="~/Default.aspx?name=$1&amp;show=$2"
ignoreCase="true"/>
<addname="Rule2"
provider="MyProviderName"
rewriteUrlParameter="ExcludeFromClientQueryString"
ignoreCase="true"/>
</rewrites>
</urlrewritingnet>

www.urlrewriting.net

Page16

Copyrightnotice

/*UrlRewritingNet.UrlRewrite
*Version2.0
*
*Copyright2006byAlbertWeinertandThomasBandt.
*
*http://deralbert.com,http://blog.thomasbandt.de
*
*Thislibraryisofferedasitis,withoutanywarranty.
*
*Thelibrarycanbeusedforfreeinfreeandcommercialprojects.
*
*Ifthislibraryisofferedothershishastobefreeofcharge.
*
*Itisallowdtochangethesourcecodeforownneeds.Byimprovingthe
*changed/improvedcodehastobepublished,eitherbysendingthecodeto
*usorbymakingitavailableonaownwebsite(ifso,youhavetonotifyus).
*Thisisnopromiseforimplementingthechangedcodeinthenextrelease.
*
*Thiscopyrightnoticehastobeplacedinthesourcecode.
*
*Itisnotallowedtocreateacommercialrewriteenginebasedonthis
*library!
*
*Basedonhttp://weblogs.asp.net/fmarguerie/archive/2004/11/18/265719.aspx
*
*Forfurtherinformationssee:http://www.urlrewriting.net/
*/

www.urlrewriting.net

Page17

You might also like