Can I interleave two MVC view engines when searchi

2019-08-11 09:57发布

问题:

I'm using the WebForms and Razor view engines in my MVC project. They work just fine together. However, I have an inheritance-based project set up, such that I have multiple child projects derived from a base project. With just one view engine, this works such that MVC will search for a view in the child projects, and failing to find it, it will search the base.

However, when adding the second view engine, this search pattern is broken, such that the WebForms engine searches the child and then the base, and then the Razor engine searches the child and then the base. As such, a base .aspx view will be given priority over a child .cshtml view. In other words, when searching for a view named MyView, this is the prioritized list of locations searched:

Child\MyView.aspx
Base\MyView.aspx
Child\MyView.cshtml
Base\MyView.cshtml

What I want is to have the two engines each check the child projects before either checks the base project, as such:

Child\MyView.aspx
Child\MyView.cshtml
Base\MyView.aspx
Base\MyView.cshtml

Is this possible, and if so, can someone point me in the right direction?

回答1:

You could write your own view engine that uses both existing view engines internally.

public InterleavedViewEngine : IViewEngine
{
    public string[] SearchLocations;

    RazorViewEngine _razor;
    WebFormsViewEngine _webForms;

    public override ViewEngineResult FindView(...)
    {
        //iterate search paths, trying Razor, then WebForms, etc...
        foreach(var location in SearchLocations)
        {
            var razorResult = _razor.FindView(...);

            if(razorResult.View == null)
            {
               //web forms, etc... here
            }

        }
    }

}