gpt4 book ai didi

c# - 如何从类库项目加载 View ?

转载 作者:太空狗 更新时间:2023-10-29 17:54:11 29 4
gpt4 key购买 nike

我尝试创建一个 VirtualPathProvider 并将 View 设置为嵌入式资源。

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;
}
}

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

private bool IsAppResourcePath(string virtualPath)
{
String checkPath = VirtualPathUtility.ToAppRelative(virtualPath);
return checkPath.StartsWith("~/App_Resource/", 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);
}
}

我的 Controller

return View("~/App_Resource/Blog.DLL/Blog.Views.Blog.Latest.cshtml");

它确实找到了 View ,但我最终得到了这个错误:

... view.cshtml' must derive from WebViewPage, or WebViewPage<TModel>.

当尝试使用以下方式显示局部 View 时:

@{ Html.RenderAction("Latest", "Blog"); }

有办法解决吗?

或者是否有一种更简单的方法在 DLL 上存储 View ?

最佳答案

发生这种情况的原因是因为您现在从未知位置提供 Razor View ,标准 ~/views/web.config 不再适用。因此,您可以将 @inherits System.Web.Mvc.WebViewPage 放入您的自定义 View 中,但这可能会很麻烦。

您可以结帐the following article .

关于c# - 如何从类库项目加载 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5467227/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com