ASP.NET Routing: How to make routeConfig handle a more dynamic URL structure

后端 未结 1 951
感情败类
感情败类 2021-01-03 09:51

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条回答
  • 2021-01-03 10:15

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

    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.

    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.

    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+" _
    })
    

    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.

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

    More info from CodeProject.

    0 讨论(0)
提交回复
热议问题