Allow empty parameter in MVC route

断了今生、忘了曾经 提交于 2019-12-13 15:59:55

问题


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.



来源:https://stackoverflow.com/questions/4447190/allow-empty-parameter-in-mvc-route

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!