Incorrect MVC Segment Identification

I have this route:
( Ignore XML format )

<route name="note" url="{noteId}-{title}">
    <constraints>
        <segment name="noteId" value="\d+" />
        <segment name="title" value=".+" />
    </constraints>
</route>

I want it to match URLs like / 1234-hello-kitty or / 5578-abc-ddd-fg

The MVC routing handler seems to have some problems with this.

I read a lot about the subject, and I learned some interesting facts:

  • MVC first identifies route segments and then checks for restrictions
  • MVC reads segments from right to left , which means that it first identifies the title and then noteId

Taking the first example, I assume that MVC identifies noteId as 1234-hello and title as kitty strong>.

This does not happen when constraints are checked, and therefore the route is not mapped.

Is there any other way to do this?

Please note that I want to keep both noteId and title segments , and they should be separated by a hyphen (this is required ) -

+4
source share
2 answers

I see a couple of options for solving this problem:

URLRewriting

, URL- ( mod_rewrite), , , MVC . IIS Module Microsoft, , ( ) . , MVC - , URL- , , , MVC. URL Rewrite - IIS, MVC, . - , MVC, . . URL- /1234-hello-kitty /1234/hello-kitty, MVC {noteId}/{*title}. , , /1234/hello-kitty, /1234-hello-kitty. , , , , {noteId}-{title}. ( ), /1234-hello-kitty ( ).

MVC

, MVC , , , . SO post , . , URL- requestContext.RouteData.Values["nodeId"] = /* your code that gets noteId out of URL. */. , .

+2

, :

  • MVC ,
  • MVC , , title, noteId

, , MVC noteId 1234-hello title .

, , .

. , , ASP.NET.

?

ASP.NET : .

, :

  • a routeUrl "/". . : "{noteId}-{title}".
  • : . {}, - . 3 : {noteId}, - {title}

( ):

  • last (-) (title).
  • 1-, . URL , .

, , , . , .

  • (, ^\d+-[\w-]+$), . URL.
  • title noteId, /hello-kitty-1234.
  • , /1234--hello-kitty.
+1

Source: https://habr.com/ru/post/1540730/


All Articles