我正在编写一个MVC应用程序,并尝试使用新类覆盖RazorViewEngine。我想看看特定控制器嵌套在哪些文件夹中。
如果我的项目设置为:
>MyProject
>>Controllers
>>>SomeGroup
>>>>AnotherGroup
>>>>>MyTestController.cs
我想返回“〜\ Controllers \ 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中,我试图从当前虚拟路径和控制器路径(我找不到)创建View的实际路径。我的类看起来像这样。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文件夹中建立一些层次结构。
答案 0 :(得分:1)
假设您还使用了控制器的默认路由,请尝试:
Request.CurrentExecutionFilePath
答案 1 :(得分:0)
你这样做有点不对劲。您不需要返回控制器的文件位置...因为它被编译成DLL。
如果您尝试命中特定的控制器MyTestController,您应该导航到以下网址http://www.example.com/MyTestController,该控制器的索引操作将会跳闸。
如果这不起作用,则表示您的默认路由存在问题。你的RouteConfig.cs应该有这个:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Deposit", action = "Index", id = UrlParameter.Optional }
);