我正在編寫一個MVC應用程序,並試圖用新類覆蓋RazorViewEngine。我想看看特定控制器嵌套在哪個文件夾中。從ControllerContext對象獲取控制器的絕對路徑
如果我的項目被設置爲:
>MyProject
>>Controllers
>>>SomeGroup
>>>>AnotherGroup
>>>>>MyTestController.cs
我想回到 「〜\控制器\ SomeGroup \ AnotherGroup \ MyTestController.cs」;
我已經梳理了ControllerContext對象的任何路徑。 我也試過:
HttpContext.Current.Server.MapPath("MyTestController.cs")
Path.GetFullPath("MyTestController.cs");
Path.GetDirectoryName("MyTestController.cs");
Path.Combine(Directory.GetCurrentDirectory(), "MyTestController.cs");
new FileInfo("MyTestController.cs").FullName;
new FileInfo("MyTestController.cs").Directory.FullName;
任何想法表示讚賞。謝謝!
編輯:我應該澄清一點。歡迎任何其他選項。我試圖將Views文件夾的文件夾結構與Controllers文件夾的文件夾結構相匹配。在RazorViewEngine中,我試圖從當前虛擬路徑和控制器路徑(我無法找到)創建視圖的實際路徑。我的類看起來像這樣。
public class MyRazorViewEngine :RazorViewEngine
{
public MyRazorViewEngine()
: base()
{
//Source: http://blog.thekfactor.info/posts/asp-net-mvc-custom-view-engines-using-the-razor-view-engine-as-the-base/
ViewLocationFormats = new string[] { "~/Views/{1}/{0}.cshtml","~/Views/%1/{1}/{0}.cshtml", "~/Views/Shared/{0}.cshtml"};
MasterLocationFormats = new string[] { "~/Views/{1}/{0}.cshtml", "~/Views/%1/{1}/{0}.cshtml", "~/Views/Shared/{0}.cshtml" };
PartialViewLocationFormats = new string[] { "~/Views/{1}/{0}.cshtml","~/Views/%1/{1}/{0}.cshtml", "~/Views/Shared/{0}.cshtml" };
FileExtensions = new string[] { "cshtml" };
}
protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
{
string parentFolderPath = GetFolderNamesBetweenControllersFolderAndControllerFromContextObject();
return base.CreateView(controllerContext, viewPath.Replace("%1", parentFolderPath), masterPath);
}
protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)
{
string parentFolderPath = GetFolderNamesBetweenControllersFolderAndControllerFromContextObject();
return base.CreatePartialView(controllerContext, partialPath.Replace("%1", parentFolderPath));
}
protected override bool FileExists(ControllerContext controllerContext, string virtualPath)
{
string parentFolderPath = GetFolderNamesBetweenControllersFolderAndControllerFromContextObject();
return base.FileExists(controllerContext, virtualPath.Replace("%1",parentFolderPath));
}
}
我不想在這裏使用區域。我只是試圖在Views文件夾中建立一些層次結構。
我試過HttpContext.Current.Request.CurrentExecutionFilePath和controllerContext.HttpContext.Request.CurrentExecutionFilePath。兩者都只是一個斜線。無內容。感謝您的建議。該代碼正在從RazorViewEngine繼承的類中調用。 – neonScarecrow