How to extend where MVC looks for views

2019-06-08 08:49发布

问题:

I an application that has a concept of discrete modules. These modules will live in Modules folder. Each module will have a folder under this Modules folder. These module folders will then have a Controllers and Views folder under them, very similar to how Areas work.

I would like to extend/change the search locations that are searched so that when my module controllers return a view the new locations will be searched.

I am thinking this will need to involve a custom ViewEngine, but I am uncertain of the specifics. Is there a specific viewengine I can extend, or do I need to write a new one from scratch.

Is writing a custom view engine the right way to go, or is there a better route?

回答1:

I am thinking this will need to involve a custom ViewEngine

Correct thinking.



回答2:

Instead of extending a specific view engine you can implement a view engine wrapper, that way your custom logic for locating views can work with multiple view engines. That's how MvcCodeRouting works, by temporarily replacing the controller value in controllerContext.RouteData.Values, so when a location format is used (such as ~/Views/{1}/{0}.aspx) you can inject into those placeholders your custom location.