在Area下添加子文件夹,并配置View Engine搜索子文件夹下的视图

Adding a sub-folder under Area and configuring View Engine to search the views in the sub-folder

我在电子商务网站上工作。该网站连接到多个第 3 方应用程序,例如 Shopify。为此,我创建了一个区域,称为 B2b(企业对企业)...

我想在 B2b 区域下为每个第 3 方创建一个子文件夹,所以文件夹结构如下所示:

请注意,OrganisationController 对所有 3rd 方都是通用的,所以我没有将它放在任何子文件夹中。

这是我的区域注册码:

public class B2bAreaRegistration : AreaRegistration
{
    public override string AreaName
    {
        get { return "B2b"; }
    }

    public override void RegisterArea(AreaRegistrationContext context)
    {
        context.MapRoute(
            "Shopify_default",
            "B2b/Shopify/{controller}/{action}/{id}",
            new { controller = "Dashboard", action = "DisplayProducts", id = UrlParameter.Optional },
            new[] { "e-commerce.Web.Areas.B2b.Controllers.Shopify" }
        );

        context.MapRoute(
            "B2b_default",
            "B2b/{controller}/{action}/{id}",
            new { action = "Index", id = UrlParameter.Optional }
        );
    }
}

现在,如果我尝试以下 URL:

https://localhost:44339/b2b/shopify/setup/install?shop=some-name

它将击中正确的控制器:

[HttpGet]
public ActionResult Install(string shop)
{
    var myViewModel = new MyViewModel(shop);
    return View(myViewModel);
}

但是视图引擎无法找到正确的视图,这是我得到的错误:

如您所见,View Engine 未搜索 Shopify 子文件夹。我想我可以通过返回视图的路径来解决这个问题,但我想知道是否有更优雅的解决方案?

我在 this tutorial

的帮助下解决了这个问题

我创建了自定义的 Razor 视图引擎:

public class ExpandedViewEngine : RazorViewEngine
{
    public ExpandedViewEngine()
    {
        var thirdPartySubfolders = new[] 
        {
            "~/Areas/B2b/Views/Shopify/{1}/{0}.cshtml"
        };

        ViewLocationFormats = ViewLocationFormats.Union(thirdPartySubfolders).ToArray();

        // use the following if you want to extend the partial locations
        // PartialViewLocationFormats = PartialViewLocationFormats.Union(new[] { "new partial location" }).ToArray();

        // use the following if you want to extend the master locations
        // MasterLocationFormats = MasterLocationFormats.Union(new[] { "new master location" }).ToArray();   
    }
}

并在 Global.asax 中将网站配置为使用上述视图引擎:

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        ViewEngines.Engines.Add(new ExpandedViewEngine());
        AreaRegistration.RegisterAllAreas();

        // more configuratins...     
    }
}