【问题标题】:MVC MapRoute not routing with required parameterMVC MapRoute 未使用必需参数进行路由
【发布时间】:2011-06-16 04:20:34
【问题描述】:

我希望我的 MVC 应用程序的 URL 类似于:

www.site.com/Bob

这又会“重定向”到 Home/Details/Bob。

我已经设置了以下 MapRoute:

    routes.MapRoute( _
Nothing, _
"{personName}", _
New With {.controller = "Home", .action = "Details", .personName = ""}, _
New With {.result = New NameConstraint()} _
)

NameConstraint 是一个 IRoutingConstraint,用于检查名称是否存在。如果它返回 true,否则返回 false,这会导致它转到第二个(和默认)MapRoute。

Public Class ListingConstraint
    Implements IRouteConstraint
    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 personName As String
        personName = CStr(values("personName"))
        If listingName = "Bob" Then  'akin to checking the database for a valid name
            Return True
        Else
            Return False
        End If
    End Function
End Class

当我致电:www.site.com/Bob 时出现问题。它正确地路由到控制器中的 Home/Details 代码,但提供的参数什么都没有。

例如 函数详细信息(ByVal id As String)作为 ActionResult 将 viewModel 调暗为新的 XViewModel(id) 返回视图(viewModel) 结束函数

id 的值设置为空,而不是预期的 Bob。

有什么想法吗?

【问题讨论】:

    标签: asp.net-mvc maproute


    【解决方案1】:

    试试这个:

     New With {.controller = "Home", _
    .action = "Details", _
    .personName = UrlParameter.Optional}, 
    

    在您的地图路线中

    PS:幸好我的名字不是 Home……

    【讨论】:

    • 对于 www.site.com 的 URL 没问题,但在 www.site.com/Bob 的情况下仍然不能工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-04
    • 2014-12-24
    相关资源
    最近更新 更多