Allow empty parameter in MVC route

2019-07-18 01:46发布

问题:

I've got a route that should only ever called by an automated process:

routes.MapRoute(
  "Automated file processing",
  "Process/{change}/{file}/{type}",
  new { controller = "C", action = "Process" }
);

Where both the file and type are optional parameters. Ideally, I'd like to be able to call

/Process/Created/Filename/Text    (with file and type)
/Process/DirectoryListing//Text   (with type only)
/Process/Created/Filename/        (with file only)

How would you acheive that optional parameter in the middle? With the example route I showed, even if I add file = "", type = "" to the route, I get:

HTTP Error 400 - Bad Request.

回答1:

You cannot have optional parameters in the middle of route. For obvious reasons only the last parameter can be optional or the routing engine cannot disambiguate between the different possible cases.



回答2:

your answer lies here: http://haacked.com/archive/2011/02/20/routing-regression-with-two-consecutive-optional-url-parameters.aspx

It discusses the problem and also provides a workaround, hope it helps!



回答3:

I believe you need to add file = UrlParameter.Optional, type = UrlParameter.Optional

For an optional middle parameter I would define another route before this one.