ASP.NET路由:如何使routeConfig处理更加动态的URL结构 [英] ASP.NET Routing: How to make routeConfig handle a more dynamic URL structure

查看:1918
本文介绍了ASP.NET路由:如何使routeConfig处理更加动态的URL结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的情况如下:场地可以是多个类别和用户也可以在多个类别类型添加过滤器的一部分,所以我的网址现在这样的:

My scenario is as follows: a venue can be part of multiple categories and users can also add filters on multiple category types, so my URLs now are like:


  1. /场地/海滩/船/ themeparks
    (这将显示有海滩和船只和themeparks所有场馆)

  2. /场地/海滩/船

  3. /场地

  1. /venues/beaches/boats/themeparks (this will display all venues that are beaches AND boats AND themeparks)
  2. /venues/beaches/boats
  3. /venues etc.

所以不同场地类型(海滩,船,themeparks等)的数目是动态和可选的。
我决定跟URLRouting去这样我就可以开始通过来获得codebehind不同的值Request.GetFriendlyUrlSegments()

So the number of different venue types (beaches, boats, themeparks etc) is both dynamic AND optional. I decided to go with URLRouting so I can start to get the different values in codebehind via Request.GetFriendlyUrlSegments()

我安装 https://www.nuget.org/packages/Microsoft .AspNet.FriendlyUrls.Core / 并手动创建在 App_Start 文件夹 RouteConfig.vb 文件。该文件包含:

I installed https://www.nuget.org/packages/Microsoft.AspNet.FriendlyUrls.Core/ and manually created a RouteConfig.vb file in App_Start folder. This file contains:

Public NotInheritable Class RouteConfig
    Private Sub New()
    End Sub
    Public Shared Sub RegisterRoutes(routes As RouteCollection)
        Dim settings = New FriendlyUrlSettings()
        settings.AutoRedirectMode = RedirectMode.Permanent
        routes.EnableFriendlyUrls(settings)
        routes.MapPageRoute("", "venues", "~/venues.aspx")
    End Sub
End Class

而在 global.aspx.vb 我说:

Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
    RouteConfig.RegisterRoutes(RouteTable.Routes)
End Sub

我删除了所有从我的应用程序重写规则,所以在 web.config中没有规则 rewriteRules.config
当我去网址: www.example.com/venues ,它正确重定向我venues.aspx。
但这个网址: www.example.com/venues/boats/outside/castles/barns/restaurants ,抛出一个404错误:

I removed ALL rewrite rules from my application, so no rules in web.config or rewriteRules.config. When I go to URL: www.example.com/venues, it correctly redirects me to venues.aspx. But this URL: www.example.com/venues/boats/outside/castles/barns/restaurants, throws a 404 error:

我还检查<一href=\"http://stackoverflow.com/questions/3523264/asp-net-4-0-url-routing-http-error-404-0-not-found\">here并尝试过,所以在Windows上启用HTTP重定向和改变的web.config:

I also checked here and tried that, so enabling http redirection on Windows and changing web.config:

的web.config

<!-- tried setting mode to On/Off/Custom -->
<customErrors mode="Off" defaultRedirect="/error/1" redirectMode="ResponseRedirect">
  <error statusCode="404" redirect="/404.aspx" />
</customErrors>

<modules runAllManagedModulesForAllRequests="true">
  <add type="aspnetforum.ForumSEOHttpModule, aspnetforum" name="ForumSEOHttpModule" />
  <remove name="UrlRoutingModule"/>
  <add name="UrlRoutingModule"
       type="System.Web.Routing.UrlRoutingModule, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />


</modules>
<handlers>
  <remove name="PHP55_via_FastCGI" />
  <remove name="PHP53_via_FastCGI" />
  <add name="ScriptCombiner" verb="POST,GET" path="ScriptCombiner.axd" preCondition="integratedMode" type="ScriptCombiner, App_Code" />

  <add name="UrlRoutingHandler"
              preCondition="integratedMode"
              verb="*"
              path="UrlRouting.axd"
              type="System.Web.HttpForbiddenHandler, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>


</handlers>

我发现,当我明确地定义 RouteConfig.vb 路由,它的工作,像这样:

I found that when I explicitly define the routes in RouteConfig.vb, it does work, like so:

routes.MapPageRoute("", "venues", "~/venues.aspx")
routes.MapPageRoute("", "venues/boats/outside/castles/barns/restaurants", "~/venues.aspx")

所以,现在网址 /场地 /场地/船/外/城堡/谷仓/餐厅的工作,但这不是动态的。由于有大量的场地类别和组合,我不想手动添加所有这些组合。我只是想匹配与 /场地开始,然后在<$ C使用方法 Request.GetFriendlyUrlSegments 所有URL $ C> venues.aspx.vb 来获得场地类别。

So now URL /venues and /venues/boats/outside/castles/barns/restaurants work, but that is not dynamic at all. Since there are a a lot of venue categories and combinations, I don't want to add all these combinations manually. I just want to match on all URLs that start with /venues and then use method Request.GetFriendlyUrlSegments in venues.aspx.vb to get the venue categories.

我怎样才能做到这一点?

How can I do this?

推荐答案

我相信你需要添加的 URL模式您的 routes.MapPageRoute 调用。

I believe you need to add URL patterns to your routes.MapPageRoute call.

一个URL模式可以包含文本值和变量占位符(简称URL参数)。的文字和占位符都位于这是由斜杠(/)字符分隔URL的部分。

A URL pattern can contain literal values and variable placeholders (referred to as URL parameters). The literals and placeholders are located in segments of the URL which are delimited by the slash (/) character.

当一个请求时,该URL被解析成段和占位符,并且变量值提供给请求处理器。这个过程类似于在查询字符串的数据被解析,并传递到请求处理程序的方式。在这两种情况下可变信息被包括在URL并传递给在键 - 值对的形式处理。对于查询字符串两个键和值是在URL中。对于路由,键是在URL模式定义的占位符名称,只有值是在URL中。

When a request is made, the URL is parsed into segments and placeholders, and the variable values are provided to the request handler. This process is similar to the way the data in query strings is parsed and passed to the request handler. In both cases variable information is included in the URL and passed to the handler in the form of key-value pairs. For query strings both the keys and the values are in the URL. For routes, the keys are the placeholder names defined in the URL pattern, and only the values are in the URL.

在一个URL模式,您可以通过在大括号括起来定义占位符({和})。你可以在一个段定​​义多个占位符,但它们必须由立即数值分开。例如,{语言} - {国家} / {}行动是有效的路由模式。然而,{语言} {国家} / {action}不有效的模式,因为占位符之间没有文本值或分隔符。因此,路由无法确定的值从为国家占位符值语言占位符分开。

In a URL pattern, you define placeholders by enclosing them in braces ( { and } ). You can define more than one placeholder in a segment, but they must be separated by a literal value. For example, {language}-{country}/{action} is a valid route pattern. However, {language}{country}/{action} is not a valid pattern, because there is no literal value or delimiter between the placeholders. Therefore, routing cannot determine where to separate the value for the language placeholder from the value for the country placeholder.

您可以使用几个不同的方法来限制​​你的路由。您可以使用正则表达式,如:

You can use a couple of different methods to constrain your routes. You can use RegEx, as in:

routes.MapRoute(name := "BlogPost", url := "blog/posts/{postId}", defaults := New With { _
    Key .controller = "Posts", _
    Key .action = "GetPost" _
}, New With { _
    Key .postId = "\d+" _
})

小小的普通防爆pression @\\ D +在code以上基本上限制了这条路线的比赛,其中的帖子ID参数包含一个或多个数字的URL。换句话说,无非是整数,请。

The tiny Regular Expression @"\d+ in the code above basically limits the matches for this route to URLs in which the postId parameter contains one or more digits. In other words, nothing but integers, please.

有关使用路由约束另一种选择是创建一个实现了 IRouteConstraint 接口的类。

The other option for using route constraints is to create a class which implements the IRouteConstraint interface.

更多信息从的$ C $的CProject。

More info from CodeProject.

这篇关于ASP.NET路由:如何使routeConfig处理更加动态的URL结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆