原文地址:http://www.cnblogs.com/huangxiufen/archive/2012/09/07/2668584.html
因为公司想要通过静动态分离的方式使得网站访问速度更快速,所以选择了分布式加载网站中的静态文件(js,css,images),当然还有另外一些方法,这边就不做深入探讨(因为我也不是很清楚有多少方法),下面介绍下通过代码方式读取web.config的配置内容,从而实现分布加载静态文件。
首先,在web.config写我们需要的配置内容:
<gitom> <!--分布式节点--> <distribution>
<!--文件版本--> <fileVersion version="20120811_test"/>
<!--enabled:表示分布式是不是可用 -->
<!--defaultServerName:默认服务器的名称 -->
<!--random:随机,是否要以随机获取服务器的方式 --> <staticServers enabled="false" defaultServerName="Cdn1" random="true"> <staticServer name="Cdn1" url="http://js.uc.gitom.cn"/> </staticServers> <!--<uploadServers enabled="true"> <uploadServer name="Cdn1" url="http://js.uc.gitom.cn"/> </uploadServers>--> </distribution> </gitom>
当然,还要做的一件事情就是声明节点,因为这些节点是我们自定义的。
View Code
第二,写一个读取的类DistributionSectionHandle.cs,写成类的方式,实现可复用。
View Code
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Configuration; 6 using System.Collections; 7 8 namespace Gitom.Configuration 9 { 10 /// <summary> 11 /// 分布式配置节 12 /// </summary> 13 public class DistributionSectionHandler : ConfigurationSection 14 { 15 public static DistributionSectionHandler DistributionConfig 16 { 17 get 18 { 19 return ConfigurationManager.GetSection("gitom/distribution") as DistributionSectionHandler; 20 } 21 } 22 23 /// <summary> 24 /// 分布式服务器集合 25 /// </summary> 26 [ConfigurationProperty("staticServers", IsDefaultCollection = false)] 27 public StaticServerConfigurationElementCollection StaticServers 28 { 29 get 30 { 31 return (StaticServerConfigurationElementCollection)base["staticServers"]; 32 } 33 } 34 35 /// <summary> 36 /// 文件版本配置节(可选) 37 /// </summary> 38 [ConfigurationProperty("fileVersion", IsRequired = false)] 39 public FileVersionConfigurationElement FileVersion 40 { 41 get { return (FileVersionConfigurationElement)base["fileVersion"]; } 42 } 43 } 44 45 /// <summary> 46 /// 文件版本配置节 47 /// </summary> 48 public class FileVersionConfigurationElement : ConfigurationElement 49 { 50 [ConfigurationProperty("version", IsRequired = true)] 51 public string Version 52 { 53 get { return (string)base["version"]; } 54 } 55 56 57 } 58 59 /// <summary> 60 /// 分布式服务器配置节 61 /// </summary> 62 public class StaticServerConfigurationElementCollection : ConfigurationElementCollection 63 { 64 65 /// <summary> 66 /// 用于缓存数据 67 /// </summary> 68 private Hashtable htServers = new Hashtable(); 69 70 /// <summary> 71 /// 是否为缓存加载,true:是,false:否 72 /// </summary> 73 private bool cacheLoaded = false; 74 75 /// <summary> 76 /// 是否启用 77 /// </summary> 78 [ConfigurationProperty("enabled", IsRequired = true)] 79 public bool Enabled 80 { 81 get { return (bool)base["enabled"]; } 82 } 83 84 /// <summary> 85 /// 是否随机选择服务器 86 /// </summary> 87 [ConfigurationProperty("random", IsRequired = false, DefaultValue = true)] 88 public bool Random 89 { 90 get { return (bool)base["random"]; } 91 } 92 93 /// <summary> 94 /// 默认服务器名,即没有随机的情况下,选择哪个名称 95 /// </summary> 96 [ConfigurationProperty("defaultServerName", IsRequired = false, DefaultValue = null)] 97 public string DefaultServerName 98 { 99 get { return (string)base["defaultServerName"]; } 100 } 101 102 public override ConfigurationElementCollectionType CollectionType 103 { 104 get 105 { 106 return ConfigurationElementCollectionType.BasicMap; 107 } 108 } 109 110 public new StaticServerConfigurationElement this[string name] 111 { 112 get 113 { 114 foreach (ConfigurationElement ce in this) 115 { 116 if ((ce as StaticServerConfigurationElement).Name == name) 117 { 118 return ce as StaticServerConfigurationElement; 119 } 120 } 121 return null; 122 } 123 } 124 125 public StaticServerConfigurationElement this[int index] 126 { 127 128 get 129 { 130 131 int tmp = 0; 132 133 foreach (StaticServerConfigurationElement serverElement in this) 134 { 135 // 第一次加载,缓存里没数据 136 if (!cacheLoaded) 137 { 138 htServers.Add(tmp, serverElement); 139 tmp++; 140 } 141 142 } 143 144 // 设置缓存加载为true 145 cacheLoaded = true; 146 147 if (htServers.Count - 1 < index) 148 { 149 return null; 150 } 151 152 return (StaticServerConfigurationElement)htServers[index]; 153 } 154 } 155 156 protected override string ElementName 157 { 158 get 159 { 160 return "staticServer"; 161 } 162 } 163 164 protected override ConfigurationElement CreateNewElement() 165 { 166 return new StaticServerConfigurationElement(); 167 } 168 169 protected override object GetElementKey(ConfigurationElement element) 170 { 171 return ((StaticServerConfigurationElement)element).Name; 172 } 173 } 174 175 public class StaticServerConfigurationElement : ConfigurationElement 176 { 177 [ConfigurationProperty("name", IsRequired = true)] 178 public string Name 179 { 180 get 181 { 182 return (string)base["name"]; 183 } 184 } 185 186 [ConfigurationProperty("url", IsRequired = true)] 187 public string Url 188 { 189 get 190 { 191 return (string)base["url"]; 192 } 193 } 194 } 195 }
第三,就是编写htmlHelper扩展类HtmlExtensions.cs,可以在cshtml页面使用。
View Code
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Web.Mvc; 6 using System.Reflection; 7 using System.Web; 8 using System.Configuration; 9 using Gitom.Configuration; 10 11 namespace Gitom.Web.Mvc3 12 { 13 public static class HtmlExtensions 14 { 15 private static long timeTicks = DateTime.Now.Ticks; 16 private static string version = ConfigurationManager.AppSettings["appver"]; 17 18 // 获得静态服务器的配置节点 19 private static StaticServerConfigurationElementCollection fileConfig = DistributionSectionHandler.DistributionConfig.StaticServers; 20 21 // 静态服务器的文件版本 22 private static string distriFileVersion = DistributionSectionHandler.DistributionConfig.FileVersion.Version; 23 24 // 静态服务器是否可用 25 private static bool fileServerEnable = fileConfig.Enabled; 26 27 // 默认服务器名,即没有随机的情况下,选择哪个名称 28 private static string defaultServerName = fileConfig.DefaultServerName; 29 30 // 是否随机选择服务器 31 private static bool random = fileConfig.Random; 32 33 /// <summary> 34 /// 生成CSS样式链接,默认采用分布式加载 35 /// </summary> 36 /// <param name="htmlHelper">在视图中呈现的HTMTL控件</param> 37 /// <param name="url">添加的文件路径</param> 38 /// <returns></returns> 39 public static MvcHtmlString Css(this HtmlHelper htmlHelper, string url) 40 { 41 return Css(htmlHelper, url, true); 42 } 43 44 /// <summary> 45 /// 生成CSS样式链接,分为debug状态和release状态,默认采用分布式加载 46 /// </summary> 47 /// <param name="htmlHelper">在视图中呈现的HTMTL控件</param> 48 /// <param name="url">debug时的文件路径</param> 49 /// <param name="releaseUrl">release时的文件路径</param> 50 /// <returns></returns> 51 public static MvcHtmlString Css(this HtmlHelper htmlHelper, string url, string releaseUrl) 52 { 53 return Css(htmlHelper, url, releaseUrl, true); 54 } 55 56 /// <summary> 57 /// 一般方式生成javacript链接,默认采用分布式加载 58 /// </summary> 59 /// <param name="htmlHelper">在视图中呈现的HTMTL控件</param> 60 /// <param name="url">添加的文件路径</param> 61 /// <returns></returns> 62 public static MvcHtmlString JavaScript(this HtmlHelper htmlHelper, string url) 63 { 64 return JavaScript(htmlHelper, url, true); 65 } 66 67 /// <summary> 68 /// 一般方式生成javacript链接,分为debug状态和release状态,默认采用分布式加载 69 /// </summary> 70 /// <param name="htmlHelper">在视图中呈现的HTMTL控件</param> 71 /// <param name="url">debug时的文件路径</param> 72 /// <param name="releaseUrl">release时的文件路径</param> 73 /// <returns></returns> 74 public static MvcHtmlString JavaScript(this HtmlHelper htmlHelper, string url, string releaseUrl) 75 { 76 return JavaScript(htmlHelper, url, releaseUrl, true); 77 } 78 79 /// <summary> 80 /// 引用分布式方式生成javacript链接 81 /// </summary> 82 /// <param name="htmlHelper">在视图中呈现的HTMTL控件</param> 83 /// <param name="url">添加的文件路径</param> 84 /// <param name="distribution">是否采用分布式加载:true->是;false->否</param> 85 /// <returns></returns> 86 public static MvcHtmlString JavaScript(this HtmlHelper htmlHelper, string url, bool distribution) 87 { 88 89 string scriptUrl = url; 90 91 if (string.IsNullOrWhiteSpace(scriptUrl)) 92 { 93 return null; 94 } 95 96 if (scriptUrl.StartsWith("~")) 97 { 98 scriptUrl = PathHelpers.GenerateClientUrl(htmlHelper.ViewContext.HttpContext, scriptUrl); 99 } 100 101 // 采用分布式加载 102 if (distribution) 103 { 104 // 如果静态服务器可用的情况下才采用静态加载 105 if (fileServerEnable) 106 { 107 scriptUrl = getDistributeUrl(scriptUrl); 108 } 109 else 110 { 111 // 静态服务器不可用的情况下 112 scriptUrl = getCommonUrl(scriptUrl); 113 } 114 } 115 else 116 { 117 // 没有采用分布式 118 scriptUrl = getCommonUrl(scriptUrl); 119 } 120 121 TagBuilder tagBuilder = new TagBuilder("script"); 122 tagBuilder.MergeAttribute("type", "text/javascript"); 123 tagBuilder.MergeAttribute("src", scriptUrl); 124 125 return MvcHtmlString.Create(tagBuilder.ToString(TagRenderMode.Normal)); 126 127 } 128 129 /// <summary> 130 /// 引用分布式方式生成javacript链接,分为debug状态和release状态 131 /// </summary> 132 /// <param name="htmlHelper">在视图中呈现的HTMTL控件</param> 133 /// <param name="url">debug时的文件路径</param> 134 /// <param name="releaseUrl">release时的文件路径</param> 135 /// <param name="distribution">是否采用分布式加载:true->是;false->否</param> 136 /// <returns></returns> 137 public static MvcHtmlString JavaScript(this HtmlHelper htmlHelper, string url, string releaseUrl, bool distribution) 138 { 139 MvcHtmlString mvcHtml = null; 140 141 if (HttpContext.Current.IsDebuggingEnabled) 142 { 143 mvcHtml = JavaScript(htmlHelper, url, distribution); 144 } 145 else 146 { 147 mvcHtml = JavaScript(htmlHelper, releaseUrl,distribution); 148 } 149 150 return mvcHtml; 151 } 152 153 /// <summary> 154 /// 引用分布式生成CSS样式链接 155 /// </summary> 156 /// <param name="htmlHelper">在视图中呈现的HTMTL控件</param> 157 /// <param name="url">添加的文件路径</param> 158 /// <param name="distribution">是否采用分布式加载:true->是;false->否</param> 159 /// <returns></returns> 160 public static MvcHtmlString Css(this HtmlHelper htmlHelper, string url, bool distribution) 161 { 162 string cssUrl = url; 163 164 if (string.IsNullOrWhiteSpace(cssUrl)) 165 { 166 return null; 167 } 168 169 if (cssUrl.StartsWith("~")) 170 { 171 cssUrl = PathHelpers.GenerateClientUrl(htmlHelper.ViewContext.HttpContext, cssUrl); 172 } 173 174 // 采用分布式加载 175 if (distribution) 176 { 177 // 如果静态服务器可用的情况下才采用静态加载 178 if (fileServerEnable) 179 { 180 cssUrl = getDistributeUrl(cssUrl); 181 182 } 183 else 184 { 185 // 静态服务器不可用的情况下 186 cssUrl = getCommonUrl(cssUrl); 187 } 188 } 189 else 190 { 191 // 没有采用分布式 192 cssUrl = getCommonUrl(cssUrl); 193 } 194 195 TagBuilder tagBuilder = new TagBuilder("link"); 196 tagBuilder.MergeAttribute("rel", "stylesheet"); 197 tagBuilder.MergeAttribute("type", "text/css"); 198 tagBuilder.MergeAttribute("href", cssUrl); 199 200 return MvcHtmlString.Create(tagBuilder.ToString(TagRenderMode.SelfClosing)); 201 202 } 203 204 /// <summary> 205 /// 引用分布式生成CSS样式链接,分为debug状态和release状态 206 /// </summary> 207 /// <param name="htmlHelper">在视图中呈现的HTMTL控件</param> 208 /// <param name="url">debug时的文件路径</param> 209 /// <param name="releaseUrl">release时的文件路径</param> 210 /// <param name="distribution">是否采用分布式加载:true->是;false->否</param> 211 /// <returns></returns> 212 public static MvcHtmlString Css(this HtmlHelper htmlHelper, string url, string releaseUrl,bool distribution) 213 { 214 MvcHtmlString mvcHtml = null; 215 216 if (HttpContext.Current.IsDebuggingEnabled) 217 { 218 mvcHtml = Css(htmlHelper, url,distribution); 219 } 220 else 221 { 222 mvcHtml = Css(htmlHelper, releaseUrl,distribution); 223 } 224 225 return mvcHtml; 226 } 227 228 /// <summary> 229 /// 获取分布式服务器的Url 230 /// </summary> 231 /// <returns></returns> 232 private static string getDistributionServerUrl() 233 { 234 // 确认哪个静态服务器的路径 235 string serverUrl = string.Empty; 236 237 // 随机加载时 238 if (random) 239 { 240 // 静态服务器的个数 241 int count = fileConfig.Count; 242 243 // 当个数大于的情况 244 if (count > 1) 245 { 246 Random rnd = new Random(); 247 int index = rnd.Next(0, count); 248 serverUrl = fileConfig[index].Url; 249 } 250 else 251 { 252 serverUrl = fileConfig[0].Url; 253 } 254 } 255 else // 不是随机加载时 256 { 257 serverUrl = fileConfig[defaultServerName].Url; 258 } 259 260 return serverUrl; 261 } 262 263 /// <summary> 264 /// 获取一般的加载Url返回路径 265 /// </summary> 266 /// <param name="url"></param> 267 /// <returns></returns> 268 private static string getCommonUrl(string url) 269 { 270 string retUrl = url; 271 272 if (HttpContext.Current.IsDebuggingEnabled) 273 { 274 if (retUrl.IndexOf("?") != -1) 275 { 276 retUrl += "&_=" + timeTicks; 277 } 278 else 279 { 280 retUrl += "?_=" + timeTicks; 281 } 282 } 283 else 284 { 285 if (retUrl.IndexOf("?") != -1) 286 { 287 retUrl += "&_=" + version; 288 } 289 else 290 { 291 retUrl += "?_=" + version; 292 } 293 } 294 295 return retUrl; 296 } 297 298 /// <summary> 299 /// 获取分布式加载Url的返回路径 300 /// </summary> 301 /// <param name="url"></param> 302 /// <returns></returns> 303 private static string getDistributeUrl(string url) 304 { 305 string retUrl = url; 306 307 // 确认哪个静态服务器的路径 308 string serverUrl = getDistributionServerUrl(); 309 310 // 调试状态下 311 if (HttpContext.Current.IsDebuggingEnabled) 312 { 313 if (retUrl.IndexOf('?') != -1) 314 { 315 retUrl += "&_=" + timeTicks; 316 } 317 else 318 { 319 retUrl += "?_=" + timeTicks; 320 } 321 } 322 else 323 { 324 if (retUrl.IndexOf('?') != -1) 325 { 326 retUrl = serverUrl + retUrl + "&_=" + distriFileVersion; 327 } 328 else 329 { 330 retUrl = serverUrl + retUrl + "?_=" + distriFileVersion; 331 } 332 } 333 334 return retUrl; 335 } 336 337 } 338 }
第四,在cshtml页面引用。
@Html.Css("~/template/default/css/all.css")
@Html.JavaScript("~/template/default/scripts/jquery-1.7.1.js", "~/template/default/scripts/jquery-1.7.1.min.js")
最后,这些都是来自我们公司项目的代码,之所以拿出来分享,是因为我觉得这里面真的有可以学习的地方,当然最要感谢的人是我的技术主管,没有他的指导我可能实现不了这样的功能。我第一次写博客,有什么不足请大家指出以改进,谢谢大家!
感谢你的阅读,如果对你有帮助,请支持我!请点[推荐]
如果有意见或建议,欢迎留言交流!
如果有意见或建议,欢迎留言交流!
欢迎转载,请保留出处,冰慧感谢你的关注与支持!