Is there any VirtualPathProvider working sample in mvc4 razor?

别等时光非礼了梦想. 提交于 2019-12-04 18:06:50
Ian Gibson

I can see the question is a bit old but I just encountered the same error. I believe the problem is the test URL. I don't have time to fully investigate but I think that unless the supplied URL is in an expected format (ASP.NET MVC view engine is conventions based) then it might not be using razor as a view engine; I'm not sure if that is the cause but some examples using the 'Infra' string you are using:

New MVC 4 Project in home controller:

public ActionResult Index()
{
    ViewBag.Message = "Welcome to ASP.NET MVC!";

    dynamic x = new ExpandoObject();

    return View("Infra-test.cshtml", x);
}

This calls into:

private bool IsPathVirtual(string virtualPath)

with virtualPath set to '/Views/Home/Infra-test.cshtml.aspx'. It has added an aspx extension onto the end which leads me to believe it is not using razor to compile the view. A small modification to the virtual path provider will see the links below working:

public override bool FileExists(string virtualPath)
{
    if (Previous.FileExists(virtualPath))
        return true;
    else
        //  prevent view start compilation errors
        return virtualPath.StartsWith("/Infra") && !virtualPath.Contains("_ViewStart");
}

URL's that will work:

return View("/Infra/test.cshtml", x);
return View("/Infra/one/test.cshtml", x);
return View("/Infra/one/two/test.cshtml", x);

these do not work:

return View("/Infra", x);
return View("/Infra/test", x);

For the sample to work you will also need to implement GetCacheDependency; otherwise, it will throw an exception when it fails to find a file for the virtual path on the disk, below is a simple example. Read the docs to implement properly.

private bool IsVirtualPath(string virtualPath)
{
    return virtualPath.StartsWith("/Infra") && !virtualPath.Contains("_ViewStart");
}

public override CacheDependency GetCacheDependency(string virtualPath, System.Collections.IEnumerable virtualPathDependencies, DateTime utcStart)
{
    if (IsVirtualPath(virtualPath))
        return null;

    return Previous.GetCacheDependency(virtualPath, virtualPathDependencies, utcStart);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!