如何在自定义剃刀视图引擎中使用相对虚拟路径
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在自定义剃刀视图引擎中使用相对虚拟路径相关的知识,希望对你有一定的参考价值。
我使用自定义剃刀视图引擎与重写MasterLocationFormats。我想为搜索视图和母版页提供相对虚拟路径位置。
怎么办?
public class ExampleRazorViewEngine : RazorViewEngine
{
/// <summary>
/// Initializes a new instance of the <see cref="ExampleRazorViewEngine"/> class.
/// </summary>
public ExampleRazorViewEngine()
{
ViewLocationFormats = new string[] {
"../../../Views/{1}/{0}.cshtml",
};
MasterLocationFormats = new string[] {
"../../../Views/{1}/{0}.cshtml",
};
PartialViewLocationFormats = new string[] {
"../../../Views/{1}/{0}.cshtml",
};
FileExtensions = new string[] { "cshtml" };
}
这样做会产生以下错误。这里不允许相对虚拟路径.. <path> ..
答案
假设您要在项目目录中的Plugins文件夹中加载视图文件。然后你的代码看起来像下面的例子。
例:
public class PluginViewEngine : RazorViewEngine
{
private List<string> _plugins = new List<string>();
public PluginViewEngine()
{
var plugins = Directory.GetDirectories(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Plugins")).ToList();
//Load your directory
plugins.ForEach(s =>
{
var di = new DirectoryInfo(s);
_plugins.Add(di.Name);
});
ViewLocationFormats = GetViewLocations();
MasterLocationFormats = GetMasterLocations();
PartialViewLocationFormats = GetViewLocations();
}
public string[] GetViewLocations()
{
var views = new List<string> {
"~/Views/{1}/{0}.cshtml"
};
_plugins.ForEach(plugin =>
views.Add("~/Plugins/" + plugin + "/Views/{1}/{0}.cshtml")
); //Load your view
return views.ToArray();
}
public string[] GetMasterLocations()
{
var masterPages = new List<string> {
"~/Views/Shared/{0}.cshtml"
};
_plugins.ForEach(plugin =>
masterPages.Add("~/Plugins/" + plugin + "/Views/Shared/{0}.cshtml")
);//Load your view
return masterPages.ToArray();
}
}
以上是关于如何在自定义剃刀视图引擎中使用相对虚拟路径的主要内容,如果未能解决你的问题,请参考以下文章