这是我的做法:
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;
}