.net routing:可以限制到某个域的路由吗?

时间:2014-03-25 18:23:43

标签: asp.net vb.net routing routes

我继承了一个处理几个域的vb.net WebForms项目。但是,我想要每个域的唯一路由。有没有办法通过在使用MapPageRoute时获取域来实现此目的?或者我需要做一些事情:

routes.MapPageRoute("r1", "example1/page1", "~/example1/default.aspx")
routes.MapPageRoute("r2", "example2/page1", "~/example2/default.aspx")

然后网址需要像:

// example1.com/example1/page1和//example2.com/example2/page1

在Application_Start,如果可能,我想限制到特定域的路由。

*编辑*

好的,看起来我能够通过为类似的路径路径创建唯一的路由名称来解决这个问题:

routes.MapPageRoute("r1", "page1", "~/example1/default.aspx")
routes.MapPageRoute("r2", "page1", "~/example2/default.aspx")

然后在我的标记中,我可以这样做:

<asp:HyperLink NavigateUrl="<%$RouteUrl:routename=r1%>" ID="link_home" runat="server">Home</asp:HyperLink>

然后在我的默认页面(或其母版页)中,我可以通过基于域重定向到相应的路径来处理“//example.com/”请求。

然而我不知道如何处理传入的请求,例如:

// example1.com/page1和//example2.com/page1。我假设第一个路由将加载任一域。有什么想法我可以做什么?

1 个答案:

答案 0 :(得分:2)

跟进我的评论:

您可以改为基于域创建约束。您需要继承IRouteConstraint接口。

您定义路线的位置:

Dim domain1Constraint As New HostConstraint("domain1.com")
routes.MapPageRoute("r1", "page1", "~/example1/default.aspx", False, Nothing, New RouteValueDictionary(New With {domain1Constraint }))

然后创建一个类HostConstraint

Imports System
Imports System.Web.Routing

Public Class HostConstraint
    Implements IRouteConstraint

    Private _host As String
    Public Sub New(ByVal host As String)
        _host = host.ToLower()
    End Sub

    Public Function Match(ByVal httpContext As HttpContextBase, _
                          ByVal route As Route, _
                          ByVal parameterName As String, _
                          ByVal values As RouteValueDictionary, _
                          ByVal routeDirection As RouteDirection) As Boolean Implements IRouteConstraint.Match

        Dim host As String = httpContext.Request.Url.Host.ToLower()

        If host.Contains(_host) Then
            Return True
        Else
            Return False
        End If
    End Function
End Class