ASP.NET-MVC中的控制器路径

ASP.NET-MVC中的控制器路径

问题描述:

如何获取控制器的路径?例如,我可以这样获得一个HtmlHelper的路径:

How do I get the path of a controller? For example, I can get the path of a HtmlHelper like this:

    private static string GetVirtualPath(HtmlHelper htmlhelper)
    {
        string virtualPath = null;
        TemplateControl tc = htmlhelper.ViewDataContainer as TemplateControl;

        if (tc != null)
        {
            virtualPath = tc.AppRelativeVirtualPath;
        }

        return virtualPath;
    }


具有控制器的程序集的路径以及具有控制器操作的类的名称。

The following will give the path to the assembly with the controller and the type name of the class with the controller action. Maybe a combination of these will give you what you're after, Aaron?

string assemblyPath = Assembly.GetExecutingAssembly().CodeBase;
string typeName = this.GetType().FullName;

例如,它们会产生

file:///C:/Projects/TestApp/TestApp.UI/bin/TestApp.UI.DLL
TestApp.UI.Controllers.TestController

如果你在标准ASP.NET MVC方式中放置和命名控制器,给你C#文件的正确完整路径:

Provided that you place and name the controllers in the 'standard' ASP.NET MVC ways, a certain combination of the above might give you the correct full path to the C# file:

C:/Projects/TestApp/TestApp.UI/Controllers/TestController.cs

或相对路径:

Controllers/TestController.cs





$ b b

以下将给出控制器操作的路由:


The following will give the route to the controller action:

1) string path = Request.Url.AbsolutePath

2) string appPath = Request.ApplicationPath;
   string absPath = Request.Url.AbsolutePath;
   string path = appPath.Length <= 1 ? 
       absPath : absPath.Replace(appPath, "");

请求TestController的Index操作的示例( http:// localhost:50027 / Test / Index ):上面的返回

Example for the request for a TestController's Index action (http://localhost:50027/Test/Index): The above returns

1) /Test/Index
2) /Test/Index

对于在 http:// localhost:50027 / blog 具有基本网址的网站,请求的示例TestController的索引操作( http:// localhost:50027 / blog / Test / Index ):以上返回

For a website with base url at http://localhost:50027/blog, example for the request for a TestController's Index action (http://localhost:50027/blog/Test/Index): The above returns

1) /blog/Test/Index
2) /Test/Index