静态化的基本理解就是,常用的资源以文本形式保存,客户端访问时无需经过程序处理,直接下载
但是不存在的文件需要经过程序处理,文件内容如果需要有更动或删除,则直接删除文件本身
1.IIS Express 添加对json mine文件支持
在IIS Express文件夹里 运行以下命令
appcmd set config /section:staticContent /+[fileExtension=‘.json‘,mimeType=‘application/json‘]
2.IIS里添加 json mine文件支持
点击添加
这样 iis 和 iis express都可以直接访问已存在的静态资源(*.json)
3. 添加路由(如果不存在的文件如何处理)
在 routeConfig.cs文件里 添加
routes.MapRoute( name: "H5Jsonp", url: "Content/H5/{filename}.json", defaults: new { controller = "H5", action = "JosnpFile" });
4.添加 controller
/// <summary> /// Json文件 /// </summary> [StaticJsonFile("H5")] public class H5Controller : Controller { /// <summary> /// JsonpFile /// </summary> /// <param name="filename">json文件名</param> /// <returns></returns> public ActionResult JosnpFile(string filename) { return Content(""); } }
5.核心代码
/// <summary> /// 文件静态化特性类 /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)] public class StaticJsonFileAttribute : ActionFilterAttribute { /// <summary> /// 文件名 /// </summary> private string FileName { get; set; } /// <summary> /// 文件扩展名 /// </summary> private string Suffix { get; set; } /// <summary> /// 静态化文件存放路径 /// </summary> private string FileDirectory { get; set; } /// <summary> /// 类型 /// </summary> private string Type { get; set; } /// <summary> /// 文件扩展字典 /// </summary> private static readonly Dictionary<string, string> FileSuffixByTypeDirectory; /// <summary> /// 文件扩展字典 /// </summary> private static Dictionary<string, object> LockDict = new Dictionary<string, object>(); /// <summary> /// .ctor /// </summary> static StaticJsonFileAttribute() { FileSuffixByTypeDirectory = new Dictionary<string, string>() { { "H5", ".json" }, }; } /// <summary> /// .ctor /// </summary> public StaticJsonFileAttribute() : this("H5") { } /// <summary> /// .ctor /// </summary> /// <param name="type"></param> public StaticJsonFileAttribute(string type) { Type = type; FileDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Type); if (FileSuffixByTypeDirectory.ContainsKey(type)) { Suffix = FileSuffixByTypeDirectory[type]; } } /// <summary> /// Action执行前过滤器 /// </summary> /// <param name="filterContext"></param> public override void OnActionExecuting(ActionExecutingContext filterContext) { if (string.IsNullOrEmpty(Suffix)) { return; } string parmaValue = null; //获取参数值 var parameterInfo = filterContext.Controller.ValueProvider.GetValue("filename"); if (parameterInfo == null) { return; } parmaValue = parameterInfo.AttemptedValue; if (string.IsNullOrEmpty(parmaValue)) { return; } FileName = parmaValue; var lockKey = Type + ":" + FileName; if (!LockDict.ContainsKey(lockKey)) { LockDict.Add(lockKey, new object()); } var fileInfo = GetFileInfoByRequestUrl(filterContext); if (fileInfo == null) { return; }//在实用时,这里应当调用相应的服务,获取数据//建议在类里设置一个IGetData 字段,由autofac自动注入,在这里直接调用即可 var dict = new Dictionary<string, string>(); dict.Add("H5.App.AdText", "你是个大笨蛋!"); var content = dict.ToJsonNoneFormat(); System.Threading.Tasks.Task.Run(() => { if (!fileInfo.Exists) { lock (LockDict[lockKey]) { //下面其实应当再加上 if(!fileInfo.exiests)的判断 FileStream fileStream = null; try { fileStream = new FileStream(fileInfo.FullName, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None); var bytes = Encoding.UTF8.GetBytes(content); fileStream.Write(bytes, 0, bytes.Length); } finally { if (fileStream != null) fileStream.Close(); } } } }); filterContext.Result = new JsonpResult("callback") { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = dict, }; } /// <summary> /// 根据请求定义文件路径 /// </summary> /// <param name="controllerContext"></param> /// <returns></returns> protected virtual FileInfo GetFileInfoByRequestUrl(ControllerContext controllerContext) { if (!string.IsNullOrWhiteSpace(FileName)) { var key = FileName.Replace(Suffix, ""); var fileName = Path.Combine(FileDirectory, string.Format("{0}{1}", key, Suffix)); return new FileInfo(fileName); } return null; } }
6. jsonp类
/// <summary> /// Jsonp 的结果 /// </summary> public class JsonpResult : JsonResult { /// <summary> /// .ctor /// Jsonp /// </summary> public JsonpResult() { this.Callback = "callback"; } /// <summary> /// .ctor /// Jsonp /// </summary> /// <param name="callback">callback</param> public JsonpResult(string callback) { this.Callback = callback; } /// <summary> /// Jsonp 回调的 function 名称,默认为 callback /// </summary> public string Callback { get; set; } /// <summary> /// ExecuteResult /// </summary> /// <param name="context">context</param> public override void ExecuteResult(ControllerContext context) { if (context == null) { throw new ArgumentNullException("context"); } var request = context.HttpContext.Request; var response = context.HttpContext.Response; string jsoncallback = (context.RouteData.Values[this.Callback] as string) ?? request[this.Callback]; if (string.IsNullOrEmpty(jsoncallback)) { jsoncallback = "callback" + DateTime.Now.Ticks.ToString(); } if (string.IsNullOrEmpty(base.ContentType)) { base.ContentType = "application/x-javascript"; } response.Write(string.Format("{0}(", jsoncallback)); response.Headers.Add("P3P", "CP=CAO PSA OUR"); response.Headers.Add("Access-Control-Allow-Origin", "*"); base.ExecuteResult(context); if (!string.IsNullOrEmpty(jsoncallback)) { response.Write(")"); } } }
7.调用
如
http://localhost:6248/content/H5/58b92c3f2213028b202298209.json?_=1488857755563&callback=fn_58b92c3f2213028b22298209
时间: 2024-10-01 21:24:50