ASP.NET MVC3来自控制器的View物理位置

时间:2012-04-12 17:28:55

标签: asp.net-mvc-3 views filepath

从动作中获取MVC动作所提供的视图的物理位置的正确方法是什么?

我需要文件的最后修改时间来发送响应标头。

2 个答案:

答案 0 :(得分:4)

获取视图物理位置的正确方法是映射其虚拟路径。可以从ViewPath BuildManagerCompiledView的{​​{1}}属性中检索虚拟路径(RazorView派生自该类,因此您的IView实例通常具有该属性。

以下是您可以使用的扩展方法:

public static class PhysicalViewPathExtension
{
    public static string GetPhysicalViewPath(this ControllerBase controller, string viewName = null)
    {
        if (controller == null)
        {
            throw new ArgumentNullException("controller");
        }

        ControllerContext context = controller.ControllerContext;

        if (string.IsNullOrEmpty(viewName))
        {
            viewName = context.RouteData.GetRequiredString("action");
        }

        var result = ViewEngines.Engines.FindView(context, viewName, null);
        BuildManagerCompiledView compiledView = result.View as BuildManagerCompiledView;

        if (compiledView != null)
        {
            string virtualPath = compiledView.ViewPath;
            return context.HttpContext.Server.MapPath(virtualPath);
        }
        else
        {
            return null;
        }
    }
}

使用类似这样的东西:

public ActionResult Index()
{
    string physicalPath = this.GetPhysicalViewPath();
    ViewData["PhysicalPath"] = physicalPath;
    return View();
}

或:

public ActionResult MyAction()
{
    string physicalPath = this.GetPhysicalViewPath("MyView");
    ViewData["PhysicalPath"] = physicalPath;
    return View("MyView");
}

答案 1 :(得分:0)

这可行:

private DateTime? GetDate(string controller, string viewName)
{
    var context = new ControllerContext(Request.RequestContext, this);
    context.RouteData.Values["controller"] = controller;
    var view = ViewEngines.Engines.FindView(context, viewName, null).View as BuildManagerCompiledView;
    var path = view == null ? null : view.ViewPath;
    return path == null ? (DateTime?) null : System.IO.File.GetLastWriteTime(path);
}