2

I ported my MVC 4 project to MVC 5 and after that my views with is embedded as resources cannot be loaded. Problem is that when mvc search for view it uses view engine witch inherit from BuildManagerViewEngine. This class use FileExistenceCache with use VirtualpathProvider with is set through constructor. By default its MapPathBased provider when I change provider to my custom in HostingEnviroment no change is made in existing FileExistenceCache instances than my view is not founded.

I change VirtualpathProvider in Route config class but its to late. What is better place for this?

Thanks

4

1 回答 1

2

而是将现有的 'IViewEngine' 子类化以使用 custom VirtualPathProviderGlobal.asax然后在文件中注册您的自定义引擎。

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        GlobalConfiguration.Configure(WebApiConfig.Register);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);

        ViewEngines.Engines.Add(new MyViewEngine());
    }

    private class MyVirtualPathProvider: VirtualPathProvider {}

    private class MyViewEngine : RazorViewEngine
    {
        public MyViewEngine()
        {
            this.VirtualPathProvider = new MyVirtualPathProvider();
        }
    }
}

通过这种方式,您还可以通过添加、将引擎插入到Engines集合中的适当位置来控制哪个引擎具有优先级。

作为替代方案,您可以使用PreApplicationStartMethodAttribute替换VirtualPathProvider,但这将在全局范围内更改 provider,对于所有标准IViewEngines。

[assembly: PreApplicationStartMethod(
    typeof(MyNamespace.MyInitializer), "Initialize")]

然后你在你的类的公共静态方法中交换提供者:

public static class MyInitializer
{
    public static void Initialize() { 
        HostingEnvironment.RegisterVirtualPathProvider(new MyVirtualPathProvider());
    }
}

Phil Haack 有一篇关于它的好帖子:ASP.NET 4 中的三个隐藏的可扩展性宝石

于 2013-10-26T02:43:45.877 回答