您的位置:首页 > Web前端 > HTML

MVC-Razor生成HTML封装

2015-11-16 16:27 543 查看
/// <summary>
/// Razor模版助手
/// </summary>
public class RazorHelper
{
private static readonly object LockObj = new object();
private static readonly ObjectCache _cache = MemoryCache.Default;

/// <summary>
/// 缓存
/// </summary>
private static ObjectCache Cache
{
get { return _cache; }
}

/// <summary>
/// 根据路径解析
/// </summary>
/// <param name="filePath">cshtml 文件地址</param>
/// <param name="obj"></param>
/// <param name="viewBags"></param>
/// <returns></returns>
public static string ParseCSHtmlFile(string filePath, object obj, DynamicViewBag viewBags = null)
{
//+ DateTime.Now.ToString("yyyy-mm-dd hh:mm:ss:fff")
string value = "";
string key = filePath + "_ParseCSHtmlFile";
var obj2 = Cache.Get(key);// Cache.Contains(key);// CacheHelper.GetCache<string>(key, "HYService.Util.RazorHelper");
if (obj2 != null)
{
value = (string)obj2;
}
else
{
FileStream fs = null;
StreamReader sr = null;
try
{
if (!File.Exists(filePath)) return string.Empty;
fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
sr = new StreamReader(fs, System.Text.Encoding.UTF8);
value = sr.ReadToEnd();
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
finally
{
if (sr != null)
sr.Close();
if (fs != null)
fs.Close();
}

if (string.IsNullOrWhiteSpace(value) == false)
{
if (Cache.Contains(key) == false)
{
lock (LockObj)
{
if (Cache.Contains(key) == false)
{
var policy = new CacheItemPolicy
{
AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(1)//.AddMinutes(2)
};
Cache.Add(key, value, policy);
}
}
}
}
}

return Engine.Razor.RunCompile(value, key, null, obj, viewBags);
}

/// <summary>
/// 根据字符串解析
/// </summary>
/// <param name="fileContext"></param>
/// <param name="obj"></param>
/// <param name="viewBags"></param>
/// <returns></returns>
public static string Parse(string fileContext, object obj, DynamicViewBag viewBags = null)
{
if (obj == null)
{
return fileContext;
}

return Engine.Razor.RunCompile(fileContext, Guid.NewGuid().ToString(), null, obj, viewBags);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  .net