找不到_ViewStart.cshtml来渲染嵌入式cshtml

时间:2018-02-24 05:34:40

标签: asp.net-mvc razor-pages

我正在尝试从dll加载MVC视图(Asp.Net MVC 5)。

设置 我有一个MVC Web应用程序项目和一个类库项目( Custom.Views ),我有/CustomViews/Views/MyView/CustomView1.cshtml

CustomView1.cshtml,它是一个嵌入式资源,

@inherits System.Web.Mvc.WebViewPage

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}


<div>
    Helloooo Custom view in action!!!!!
</div>

在我的Custom.Views项目中,我有一个名为MyView controller的控制器,

public ActionResult Shop()
    {
        return View("~/ClientView/Custom.Views.DLL/Custom.Views.CustomViews.Views.MyView.CustomView1.cshtml");
    }

返回指向嵌入资源的虚拟视图路径。我配置了Route配置来检查这个命名空间&#34; Custom.Views.CustomViews ..&#34;控制器。

我实施了VirtualPathProvider

public class AssemblyResourceProvider : System.Web.Hosting.VirtualPathProvider
{
    public AssemblyResourceProvider() { }

    private bool IsAppResourcePath(string virtualPath)
    {
        String checkPath = VirtualPathUtility.ToAppRelative(virtualPath);
        return checkPath.StartsWith("~/ClientView/", StringComparison.InvariantCultureIgnoreCase);
    }

    public override bool FileExists(string virtualPath)
    {
        return (IsAppResourcePath(virtualPath) ||
                base.FileExists(virtualPath));
    }

    public override VirtualFile GetFile(string virtualPath)
    {
        if (IsAppResourcePath(virtualPath))
            return new AssemblyResourceVirtualFile(virtualPath);
        else
            return base.GetFile(virtualPath);
    }

    public override CacheDependency GetCacheDependency(string virtualPath,
        IEnumerable virtualPathDependencies, DateTime utcStart)
    {
        if (IsAppResourcePath(virtualPath))
            return null;
        else
            return base.GetCacheDependency(virtualPath, virtualPathDependencies, utcStart);
    }
}

class AssemblyResourceVirtualFile : VirtualFile
{
    string path;

    public AssemblyResourceVirtualFile(string virtualPath)
        : base(virtualPath)
    {
        path = VirtualPathUtility.ToAppRelative(virtualPath);
    }

    public override System.IO.Stream Open()
    {
        string[] parts = path.Split('/');
        string assemblyName = parts[2];
        string resourceName = parts[3];

        assemblyName = Path.Combine(HttpRuntime.BinDirectory, assemblyName);
        var assembly = Assembly.LoadFile(assemblyName);

        if (assembly != null)
        {
            return assembly.GetManifestResourceStream(resourceName);
        }
        return null;
    }
}

问题

问题1.当我输入url&#34; httlp:// localhost:1234 / myview / shop&#34;它命中虚拟路径并返回查找文件流。那部分工作正常。但不久之后,虚拟路径提供程序在&#34;〜/ ClientView / Custom.Views.DLL / _ViewStart.cshtml&#34;中获取另一个查找_ViewStart.cshtml的请求。为什么会这样? 为什么它在该路径中寻找_ViewStart.cshtml。

1 个答案:

答案 0 :(得分:0)

您可以尝试在 _ViewStart.cshtml 中定义布局页面:

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

如果您为多个视图使用不同的布局页面,您还可以为每个视图定义相应的布局页面,如下所示:

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

希望这会有所帮助......