ASP.NET MVC getting last modified date/FileInfo of View

核能气质少年 提交于 2019-12-19 03:54:06

问题


I'm required to include the last modified date on every page of my applications at work. I used to do this by including a reference to <%= LastModified %> at the bottom of my WebForms master page which would return the last modified date of the current .aspx page. My code would even check the associated .aspx.cs file, compare the last modified dates, and return the most recent date.

Does anyone know if you can read the FileInfo of a MVC View? I would like to include it in the master page, if possible.

I have a base controller that all wired up and ready to go. All I need to know is how to access the FileInfo of the current view.

namespace MyMVCApp.Controllers
{
    public abstract class SiteController : Controller
    {
        public SiteController()
        {
            ViewData["modified"] = NEED TO GET FILEINFO OF CURRENT VIEW HERE;
        }
    }
}

回答1:


You need to know the physical file of the View, which is only known when the view is being processed, so we delay the work until then:

At the bottom of the view file, just add:

Last Modified Date: @File.GetLastWriteTime(this.Server.MapPath(this.VirtualPath))

NOTE: It must be in the view file you want the date for. If you put it in the layout file, it will give you the date of that file. However, you can get the date into the footer using a section

In View:

@section lastwrite
{
    Last Modified Date: @File.GetLastWriteTime(this.Server.MapPath(this.VirtualPath))
}

in layout:

@RenderSection("lastwrite", required: false)



回答2:


The following will give you the date of the last time the view was written:

// Last Modified Date
var strPath = Request.PhysicalPath;
ViewBag.LastUpdated = System.IO.File.GetLastWriteTime(strPath).ToString();

Noticed that I used ViewBag instead of ViewData.




回答3:


Try this:

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);
}


来源:https://stackoverflow.com/questions/1529417/asp-net-mvc-getting-last-modified-date-fileinfo-of-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!