如何根据域/主机调整ASP.NET URL路由?
-
04-10-2019 - |
题
基于域/sub域/主机在global.asax Application_start事件中创建的路由表的路径目标的最佳方法是什么?以下在IIS6中有效,但是使用IIS7,请求对象与Application_start事件分离,因此不再起作用:
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")
解决方案
我似乎解决了自己的问题。您无法在IIS7.0上访问application_start上的请求对象,尽管您可以在自定义路由约束中使用它。这就是我做的。
定义自定义路由约束:
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
然后定义路线:
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")
)
该技术也可以用于基于子域的不同路由。
非常感谢史蒂文·沃瑟(Steven Wather's) ASP.NET MVC路由 张贴我指向正确的方向(即使是用于MVC而不是Web表单)。
其他提示
不隶属于 StackOverflow