假设我有一个具有视图的路径的路由值,例如

new
{
    controller = "Home",
    action = "Index"
}


如何将此映射到~/Views/Home/Index.cshtml

我知道并非所有视图都必须有一个操作,并且并不是所有操作都必须返回一个视图,因此可能会成为问题。

更新:

也许是这样的:

IView view = ViewEngines.Engines.FindView(ControllerContext, "Index").View;
view.GetViewPath();


但这允许我指定一个控制器,而不是假设我想使用我的controllerContext(或者甚至为我想要的Controller(字符串)模拟controllerContext。

最佳答案

这是我的操作方法:

private string GetPhysicalPath(string viewName, string controller)
{
    ControllerContext context = CloneControllerContext();

    if (!controller.NullOrEmpty())
    {
        context.RouteData.Values["controller"] = controller;
    }
    if (viewName.NullOrEmpty())
    {
        viewName = context.RouteData.GetActionString();
    }
    IView view = ViewEngines.Engines.FindView(viewName, context).View;
    string physicalPath = view.GetViewPath();
    return physicalPath;
}


GetViewPath的扩展方法是:

public static string GetViewPath(this IView view)
{
    BuildManagerCompiledView buildManagerCompiledView = view as BuildManagerCompiledView;
    if (buildManagerCompiledView == null)
    {
        return null;
    }
    else
    {
        return buildManagerCompiledView.ViewPath;
    }
}


CloneControllerContext是:

private ControllerContext CloneControllerContext()
{
    ControllerContext context = new ControllerContext(Request.RequestContext, this);
    return context;
}

09-28 14:20