Help with MVC 3 Routes
I have a simple route structure in my MVC 3 app that is breaking in an unexpected way.
My URL structure is fairly simple, but contains a handful of variables.
http://site.com/{location}/{stage}/{controller}/{action}/{id}
examples:
- http://site.com/ny/prod/server/list - list all prod servers in ny
- http://site.com/ny/test/server/123456 - list the details for the server in ny, in the test stage, with id 123456
- http://site.com/ny/prod/server/reboot/565656 - reboot the server in ny, in the prod stage, with id 565656
I开发者_如何学C created the following route in my Global.asax file.
routes.MapRoute("Default", "{location}/{stage}/{controller}/{action}/{id}", new {controller="server", action="list", id = UrlParameter.Optional});
This works fine for displaying a list of servers and the details of a server at /server/details/id, but when I try to execute a reboot, I get an error.
URL: http://site.com/ny/prod/server/reboot/565656
The view 'ny' or its master was not found or no view engine supports the searched locations. The following locations were searched: ...
Why would it try to look for a view name ny.cshtml?
i think your problem is that you are either not using a constraint to define what location and stage should look like and it is giving you false positives and reading things in where they are not supposed to or you have your route definitions in the wrong order
make sure you have the default mvc defined last and if you have multiple custom routes constrain the either using a regex or custom constraint class to define what locations are valid and they should look like
eg http://site.com/ny/test/server/123456
is ny a valid location - make a custom constraint that defines what a valid location is validate it against a database or a list of valid locations
is test a valid stage - regex could be sufficient but i always try to avoid regex whenever possible as it is evil and hard to maintain. again i would write a custom constraint to define what stages are valid likely validating against a list is sufficient is the case as you shouldnt have very many stages also to be noted with using stages the way you are in your url you can also add authentication rules in a constraint so that for exaple only people that are ..say.. admin or stakeholder roles be mached to the route and regular or non authenticated users would simply fall through to the next route or can simply give a 404
writing routes can be tricky so it is advised to contrain your input data as much as you can especially if you are accepting string data
stephen walther has a good post on writing route constraint at his blog
精彩评论