アクション内から MVC アクションによって提供されるビューの物理的な場所を取得する適切な方法は何ですか?
応答ヘッダーを送信するために、ファイルの最終変更時刻が必要です。
アクション内から MVC アクションによって提供されるビューの物理的な場所を取得する適切な方法は何ですか?
応答ヘッダーを送信するために、ファイルの最終変更時刻が必要です。
ビューの物理的な場所を取得する適切な方法は、その仮想パスをマップすることです。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");
}
それはうまくいくかもしれません:
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);
}