How to set up asp.net url routing based on domain / host?
What is the best way to configure the path address for the routing table created in the global.asax Application_Start event based on domain / subdomain / host? The following was done in IIS6, but as of IIS7, the request object was decoupled from the Application_Start event and therefore no longer works:
Dim strHost As String = Context.Request.Url.Host
Dim strDir As String = ""
If strHost.Contains("domain1.com") Then
strDir = "area1/"
Else
strDir = "area2/"
End If
routes.MapPageRoute("Search", "Search", "~/" & strDir & "search.aspx")
+2
a source to share
2 answers
I seem to have solved my problem. You cannot access the Request object in Application_Start using IIS7.0, although you can use it in a custom route restriction. This is how I did it.
Define a custom route restriction:
Imports System.Web
Imports System.Web.Routing
Public Class ConstraintHost
Implements IRouteConstraint
Private _value As String
Sub New(ByVal value As String)
_value = value
End Sub
Public Function Match(ByVal httpContext As System.Web.HttpContextBase, ByVal route As System.Web.Routing.Route, ByVal parameterName As String, ByVal values As System.Web.Routing.RouteValueDictionary, ByVal routeDirection As System.Web.Routing.RouteDirection) As Boolean Implements System.Web.Routing.IRouteConstraint.Match
Dim hostURL = httpContext.Request.Url.Host.ToString()
Return hostURL.IndexOf(_value, StringComparison.OrdinalIgnoreCase) >= 0
End Function
End Class
Then define a route:
routes.MapPageRoute(
"Search_Area1",
"Search",
"~/area1/search.aspx",
True,
Nothing,
New RouteValueDictionary(New With {.ArbitraryParamName = New ConstraintHost("domain1.com")})
)
routes.MapPageRoute(
"Search_Area2",
"Search",
"~/area2/search.aspx")
)
This method can also be used to apply different subdomain based routing.
Many thanks to Stephen Vater's asp.net mvc routing post for pointing me in the right direction (although this was for mvc, not web form).
+4
a source to share