4

アクション内から MVC アクションによって提供されるビューの物理的な場所を取得する適切な方法は何ですか?

応答ヘッダーを送信するために、ファイルの最終変更時刻が必要です。

4

2 に答える 2

4

ビューの物理的な場所を取得する適切な方法は、その仮想パスをマップすることです。ViewPath仮想パスはのプロパティから取得できますBuildManagerCompiledView(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");
}
于 2012-04-12T18:48:22.230 に答える
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);
}
于 2013-12-09T08:27:30.483 に答える