web优化之-Asp.net MVC js、css动态合并 动态压缩 (2)
1.5.1.js,Scripts/jquery.validate.js这在http请求时路径比较长,为此我们可以改用[Scripts/jquery-1.5.1,jquery.validate]这种格式。
修改后的代码:
CombineFiles:
[csharp]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Text;
using Yahoo.Yui.Compressor;
/// <summary>
/// CombineFiles 的摘要说明
/// </summary>
public class CombineFiles : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/javascript";
HttpRequest request = context.Request;
HttpResponse response = context.Response;
string[] allkeys = request.QueryString.AllKeys;
if (!allkeys.Contains("href") || !allkeys.Contains("type") || !allkeys.Contains("compress"))
{
response.Write("请求格式不正确,正确格式是type=....&href=....&compress=...\r\n");
response.Write("type只能是js或则css,compress只能是true或则false,href则是请求的文件,多个文件已逗号分隔\r\n");
response.Write("示例如下:\r\n type=js&compress=true&href=[Scripts/jquery-1.5.1,jquery.validate][Scripts/MicrosoftAjax]");
}
else
{
string cacheKey = request.Url.Query;
#region /*确定合并文件类型*/
string fileType = request.QueryString["type"].Trim().ToLower();
string contenType = string.Empty;
if (fileType.Equals("js"))
{
contenType = "text/javascript";
}
else if (fileType.Equals("css"))
{
contenType = "text/css";
}
/*确定合并文件类型*/
#endregion
CacheItem cacheItem = HttpRuntime.Cache.Get(cacheKey) as CacheItem;//服务端缓存
if (cacheItem == null)
{
#region 合并压缩文件
/*合并文件*/
string href = context.Request.QueryString["href"].Trim();
string content = string.Empty;
string[] files = GetFilePath(href);
StringBuilder sb = new StringBuilder();
foreach (string fileName in files)
{
string filePath = context.Server.MapPath(fileName + "." + fileType);
if (File.Exists(filePath))
{
string readstr = File.ReadAllText(filePath, Encoding.UTF8);
sb.Append(readstr);
//content = JavaScriptCompressor.Compress(content);
//response.Write(content);
}
else
{
sb.AppendLine("\r\n未找到源文件&quo
补充:Web开发 , 其他 ,