如何根据域/主机调整asp.net URL路由?

时间:2010-05-08 23:25:15

标签: asp.net iis-7 asp.net-routing

根据域/子域/主机调整在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") 

2 个答案:

答案 0 :(得分:4)

我似乎已经解决了我自己的问题。尽管可以在自定义路由约束中使用它,但无法使用IIS7.0访问Application_Start上的Request对象。我就是这样做的。

定义自定义路线约束:

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的asp.net mvc routing帖子,指出我正确的方向(即使它是用于mvc而不是网络表单)。

答案 1 :(得分:0)

这是您可以从web.config读取的设置吗? < - 我的推荐。

这篇文章有帮助吗?

http://mvolo.com/blogs/serverside/archive/2007/11/10/Integrated-mode-Request-is-not-available-in-this-context-in-Application_5F00_Start.aspx