MVC自定义视图引擎FileExists始终返回false

时间:2017-08-04 22:04:32

标签: c# asp.net-mvc razor asp.net-mvc-5

我正在尝试实现一个继承自RazerViewEngine

的自定义ViewEngine
public class MultiTenantViewEngine : RazorViewEngine
{
    public MultiTenantViewEngine()
    {
        ViewLocationFormats = new[]
        {
            "~/Views/%tenant%/{1}/{0}.cstml",
            "~/Views/{1}/{0}.cstml",
            "~/Views/%tenant%/Shared/{0}.cshtml",
            "~/Views/Shared/{0}.cshtml",
        };

    }

    protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
    {
        var controller = controllerContext.Controller as MultiTenantMVCController;
        var newViewPath = viewPath.Replace("%tenant%", controller.Tenant.Name);
        var newMasterPath = masterPath.Replace("%tenant%", controller.Tenant.Name);
        return base.CreateView(
            controllerContext,
            newViewPath,
            newMasterPath);
    }

    protected override bool FileExists(ControllerContext controllerContext, string virtualPath)
    {
        var controller = controllerContext.Controller as MultiTenantMVCController;
        var newVirtualPath = virtualPath.Replace("%tenant%", controller.Tenant.Name);
        var exists = base.FileExists(controllerContext, newVirtualPath);
        return exists;
    }
}

ViewEngine类在Application_Start中注册,并且FileExists方法被命中。它现在检查文件~/Views/Foo/Home/Index.cstml是否存在,它确实存在,但确实返回false。

然后我收到黄色死亡屏幕,并显示以下错误消息:

[InvalidOperationException: The View "Index" ...:
~/Views/%tenant%/Home/Index.cstml
~/Views/Home/Index.cstml
~/Views/%tenant%/Shared/Index.cshtml
~/Views/Shared/Index.cshtml]

使用

检查路径
System.IO.File.Exists(controllerContext.HttpContext.Server.MapPath(newVirtualPath));

也会返回false,但如果我复制该路径并直接在资源管理器中打开它就可以了。

我在这里做错了什么?

0 个答案:

没有答案