Friday, 23 September 2016

Force browsers to get latest js and css files in asp.net

1. Crete a class named FileUtility

using System.Web;

public class FileUtility
{
    public static string SetJsVersion(HttpContext context, string filename)
    {
        string version = GetJsFileVersion(context, filename);
        return filename + version;
    }

    private static string GetJsFileVersion(HttpContext context, string filename)
    {
        if (context.Cache[filename] == null)
        {
            string filePhysicalPath = context.Server.MapPath(filename);

            string version = "?v=" + GetFileLastModifiedDateTime(context, filePhysicalPath, "yyyyMMddhhmmss");

            return version;
        }
        else
        {
            return string.Empty;
        }
    }

    public static string GetFileLastModifiedDateTime(HttpContext context, string filePath, string dateFormat)
    {
        return new System.IO.FileInfo(filePath).LastWriteTime.ToString(dateFormat);
    }
}

2.Rendered HTML 
For Css : <link href="<%=FileUtility.SetJsVersion(Context,"css/bootstrap.css")%>" rel="stylesheet" />
For js : <script type="text/javascript" src='<%=FileUtility.SetJsVersion(Context,"/js/json.js") %>'></script>

No comments:

Post a Comment

Get all non-clustered indexes

DECLARE cIX CURSOR FOR     SELECT OBJECT_NAME(SI.Object_ID), SI.Object_ID, SI.Name, SI.Index_ID         FROM Sys.Indexes SI             ...