Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I combine CatchAll and EndsWith in an MVC route?

The following route will match any folder structure below BasePath:

http://BasePath/{*SomeFolders}/ 

How do I create another route which will match any zip file below the same BasePath structure?

I tried this...

http://BasePath/{*SomeFolders}/{ZipFile}

... but it errors with

A path segment that contains more than one section, such as a literal section or a parameter, cannot contain a catch-all parameter. Parameter name: routeUrl

How should I approach this?

*Update*

The original requirements are in fact flawed. {ZipFile} will match the final section regardless of what it contains. (File or Folder)

In reality I believe the route pattern I'm looking to match should be:

http://BasePath/{*SomeFolders}/{ZipFile}.zip
like image 267
Rory Becker Avatar asked Apr 11 '12 21:04

Rory Becker


1 Answers

It seems that constraints are the answer here.

    routes.MapRoute( _
        "ViewFile", "BasePath/{*RestOfPath}", _
        New With {.controller = "File", .action = "DownloadFile"}, _
        New With {.RestOfPath = ".*\.zip"}
    )
    routes.MapRoute( _
        "ViewFolder", "BasePath/{*RestOfPath}", _
        New With {.controller = "Folder", .action = "ViewFolder"} _
    )

or for those of you who prefer C#...

    routes.MapRoute( 
        "ViewFile", "BasePath/{*RestOfPath}", 
        new {controller = "File", action = "DownloadFile"}, 
        new {RestOfPath = @".*\.zip"}
    );
    routes.MapRoute( 
        "ViewFolder", "BasePath/{*RestOfPath}", 
        new {controller = "Folder", action = "ViewFolder"} 
    );

(Erm I think that's right)

The same route is registered twice, with the first variation being given the additional constraint that the RestOfPath parameter should end with ".zip"

I am given to understand that Custom Constraints are also possible using derivatives of IRouteConstraint.

like image 194
Rory Becker Avatar answered Sep 20 '22 02:09

Rory Becker