C# ;附加到每个文件开头的字符
我下载了一个HttpHandler类,它将JS文件连接到一个文件中,并在连接的每个文件的开头不断添加C# ;附加到每个文件开头的字符,c#,asp.net,encoding,httphandler,byte-order-mark,C#,Asp.net,Encoding,Httphandler,Byte Order Mark,我下载了一个HttpHandler类,它将JS文件连接到一个文件中,并在连接的每个文件的开头不断添加ï»字符 你知道这是什么原因吗?是否文件一经处理就会写入缓存,而缓存就是这样存储/呈现文件的 如有任何意见,将不胜感激 using System; using System.Net; using System.IO; using System.IO.Compression; using System.Text; using System.Configuration; using System.We
ï»
字符
你知道这是什么原因吗?是否文件一经处理就会写入缓存,而缓存就是这样存储/呈现文件的
如有任何意见,将不胜感激
using System;
using System.Net;
using System.IO;
using System.IO.Compression;
using System.Text;
using System.Configuration;
using System.Web;
public class HttpCombiner : IHttpHandler {
private const bool DO_GZIP = false;
private readonly static TimeSpan CACHE_DURATION = TimeSpan.FromDays(30);
public void ProcessRequest (HttpContext context) {
HttpRequest request = context.Request;
// Read setName, contentType and version. All are required. They are
// used as cache key
string setName = request["s"] ?? string.Empty;
string contentType = request["t"] ?? string.Empty;
string version = request["v"] ?? string.Empty;
// Decide if browser supports compressed response
bool isCompressed = DO_GZIP && this.CanGZip(context.Request);
// Response is written as UTF8 encoding. If you are using languages
// like Arabic, you should change this to proper encoding
UTF8Encoding encoding = new UTF8Encoding(false);
// If the set has already been cached, write the response directly
// from cache. Otherwise generate the response and cache it
if (!this.WriteFromCache(context, setName, version, isCompressed,
contentType))
{
using (MemoryStream memoryStream = new MemoryStream(5000))
{
// Decide regular stream or GZipStream based on whether the
// response can be cached or not
using (Stream writer = isCompressed
? (Stream)(new GZipStream(memoryStream,
CompressionMode.Compress))
: memoryStream)
{
// Load the files defined in <appSettings> and process
// each file
string setDefinition = System.Configuration
.ConfigurationManager.AppSettings[setName] ?? "";
string[] fileNames = setDefinition.Split(
new char[] { ',' },
StringSplitOptions.RemoveEmptyEntries);
foreach (string fileName in fileNames)
{
byte[] fileBytes = this.GetFileBytes(
context, fileName.Trim(), encoding);
writer.Write(fileBytes, 0, fileBytes.Length);
}
writer.Close();
}
// Cache the combined response so that it can be directly
// written in subsequent calls
byte[] responseBytes = memoryStream.ToArray();
context.Cache.Insert(
GetCacheKey(setName, version, isCompressed),
responseBytes, null,
System.Web.Caching.Cache.NoAbsoluteExpiration,
CACHE_DURATION);
// Generate the response
this.WriteBytes(responseBytes, context, isCompressed,
contentType);
}
}
}
private byte[] GetFileBytes(HttpContext context, string virtualPath,
Encoding encoding)
{
if (virtualPath.StartsWith("http://",
StringComparison.InvariantCultureIgnoreCase))
{
using (WebClient client = new WebClient())
{
return client.DownloadData(virtualPath);
}
}
else
{
string physicalPath = context.Server.MapPath(virtualPath);
byte[] bytes = File.ReadAllBytes(physicalPath);
// TODO: Convert unicode files to specified encoding.
// For now, assuming files are either ASCII or UTF8
return bytes;
}
}
private bool WriteFromCache(HttpContext context, string setName,
string version, bool isCompressed, string contentType)
{
byte[] responseBytes = context.Cache[GetCacheKey(setName, version,
isCompressed)] as byte[];
if (null == responseBytes || 0 == responseBytes.Length) return false;
this.WriteBytes(responseBytes, context, isCompressed, contentType);
return true;
}
private void WriteBytes(byte[] bytes, HttpContext context,
bool isCompressed, string contentType)
{
HttpResponse response = context.Response;
response.AppendHeader("Content-Length", bytes.Length.ToString());
response.ContentType = contentType;
if (isCompressed)
response.AppendHeader("Content-Encoding", "gzip");
context.Response.Cache.SetCacheability(HttpCacheability.Public);
context.Response.Cache.SetExpires(DateTime.Now.Add(CACHE_DURATION));
context.Response.Cache.SetMaxAge(CACHE_DURATION);
context.Response.Cache.AppendCacheExtension(
"must-revalidate, proxy-revalidate");
response.OutputStream.Write(bytes, 0, bytes.Length);
response.Flush();
}
private bool CanGZip(HttpRequest request)
{
string acceptEncoding = request.Headers["Accept-Encoding"];
if (!string.IsNullOrEmpty(acceptEncoding) &&
(acceptEncoding.Contains("gzip")
|| acceptEncoding.Contains("deflate")))
return true;
return false;
}
private string GetCacheKey(string setName, string version,
bool isCompressed)
{
return "HttpCombiner." + setName + "." + version + "." + isCompressed;
}
public bool IsReusable
{
get { return true; }
}
}
使用系统;
Net系统;
使用System.IO;
使用系统IO压缩;
使用系统文本;
使用系统配置;
使用System.Web;
公共类HttpCombiner:IHttpHandler{
private const bool DO_GZIP=false;
私有只读静态TimeSpan缓存\u DURATION=TimeSpan.FromDays(30);
公共void ProcessRequest(HttpContext上下文){
HttpRequest请求=context.request;
//读取setName、contentType和version。所有这些都是必需的。它们是
//用作缓存密钥
string setName=请求[“s”]??string.Empty;
string contentType=request[“t”]??string.Empty;
字符串版本=请求[“v”]??字符串。空;
//决定浏览器是否支持压缩响应
bool isCompressed=DO_GZIP&&this.CanGZip(context.Request);
//响应写为UTF8编码。如果您使用的是语言
//像阿拉伯语一样,您应该将其更改为正确的编码
UTF8Encoding编码=新的UTF8Encoding(假);
//如果集合已经被缓存,则直接写入响应
//否则生成响应并缓存它
如果(!this.WriteFromCache)已压缩(上下文、集合名、版本、,
contentType)
{
使用(MemoryStream MemoryStream=新的MemoryStream(5000))
{
//根据
//响应是否可以缓存
使用(流编写器=isCompressed)
?(流)(新GZipStream(memoryStream,
压缩模式
:内存流)
{
//加载和进程中定义的文件
//每个文件
字符串setDefinition=System.Configuration
.ConfigurationManager.AppSettings[setName]??“”;
string[]filename=setDefinition.Split(
新字符[]{,'},
StringSplitOptions.RemoveEmptyEntries);
foreach(文件名中的字符串文件名)
{
byte[]fileBytes=this.GetFileBytes(
上下文,fileName.Trim(),编码);
Write.Write(fileBytes,0,fileBytes.Length);
}
writer.Close();
}
//缓存组合响应,以便可以直接
//在随后的通话中写入
字节[]响应字节=memoryStream.ToArray();
context.Cache.Insert(
GetCacheKey(设置名称、版本、isCompressed),
响应字节,空,
System.Web.Caching.Cache.NoAbsoluteExport,
缓存时间);
//生成响应
this.WriteBytes(responseBytes、context、isCompressed、,
内容类型);
}
}
}
私有字节[]GetFileBytes(HttpContext上下文,字符串virtualPath,
编码
{
if(virtualPath.StartsWith)(“http://”,
StringComparison.InvariantCultureInogoreCase)
{
使用(WebClient=newWebClient())
{
返回client.DownloadData(virtualPath);
}
}
其他的
{
字符串physicalPath=context.Server.MapPath(virtualPath);
byte[]bytes=File.ReadAllBytes(物理路径);
//TODO:将unicode文件转换为指定的编码。
//现在,假设文件是ASCII或UTF8
返回字节;
}
}
私有bool WriteFromCache(HttpContext上下文,字符串setName,
字符串版本,布尔压缩,字符串内容类型)
{
byte[]responseBytes=context.Cache[GetCacheKey(setName,version,
isCompressed)]作为字节[];
if(null==responseBytes | | 0==responseBytes.Length)返回false;
this.WriteBytes(responseBytes,context,isCompressed,contentType);
返回true;
}
私有void WriteBytes(字节[]字节,HttpContext上下文,
bool是压缩的,字符串contentType)
{
HttpResponse response=context.response;
AppendHeader(“Content-Length”,bytes.Length.ToString());
response.ContentType=ContentType;
如果(已压缩)
AppendHeader(“内容编码”、“gzip”);
context.Response.Cache.SetCacheability(HttpCacheability.Public);
context.Response.Cache.SetExpires(DateTime.Now.Add(Cache_DURATION));
context.Response.Cache.SetMaxAge(缓存持续时间);
context.Response.Cache.AppendCacheExtension(
“必须重新验证,代理重新验证”);
response.OutputStream.Write(字节,0,字节.长度);
response.Flush();
}
私有bool-CanGZip(HttpRequest请求)
{
字符串acceptEncoding=request.Headers[“acceptEncoding”];
如果(!string.IsNullOrEmpty(acceptEncoding)&&
(acceptEncoding.Contains(“gzip”)
||acceptEncoding.Contains(“deflate”))
返回true;
返回false;
}
私有字符串GetCacheKey(字符串集合名、字符串版本、,
布尔(压缩)
{
返回“HttpCombiner.”+setName+“+version+”+isCompressed;
}
公共布尔可重用
{
获取{return tr
context.Response.Clear();
byte[] bytes = File.ReadAllBytes(physicalPath);
// TODO: Convert unicode files to specified encoding. For now, assuming
// files are either ASCII or UTF8
byte[] bytes = File.ReadAllBytes(physicalPath);
String ss = new StreamReader(new MemoryStream(bytes), true).ReadToEnd();
byte[] b = StrToByteArray(ss);
return b;
public static byte[] StrToByteArray(string str)
{
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
return encoding.GetBytes(str);
}