从ControllerContext对象获取控制器的绝对路径
本文关键字:路径 控制器 ControllerContext 对象 获取 | 更新日期: 2023-09-27 18:00:28
我正在编写一个MVC应用程序,并试图用一个新类覆盖RazorViewEngine。我想看看特定控制器嵌套在哪些文件夹中。
如果我的项目设置为:
>MyProject
>>Controllers
>>>SomeGroup
>>>>AnotherGroup
>>>>>MyTestController.cs
我想返回"~''Controllers''SomeGroup''AanotherGroup''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文件夹中建立一些层次结构。
假设您也使用到控制器的默认路由,那么尝试:
Request.CurrentExecutionFilePath
您这样做有点不正确。您不需要返回控制器的文件位置。。。因为它被编译成DLL。
如果你试图点击一个特定的控制器,MyTestController,你应该导航到下面的urlhttp://www.example.com/MyTestController并且该控制器的索引动作将跳闸。
如果这不起作用,那么您的默认路由有问题。你的RouteConfig.cs应该有这个:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Deposit", action = "Index", id = UrlParameter.Optional }
);