开发者

Allow empty parameter in MVC route

开发者 https://www.devze.com 2023-01-31 04:33 出处:网络
I\'ve got a route that should only ever called by an automated process: routes.MapRoute( \"Automated file processing\",

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//Tex开发者_如何学Ct   (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.


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.


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!


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消