2011-02-10 4 views
1

Firefox에서 Google Page Speed를 사용하여 내 사이트 시드를 최적화하고 있습니다. Visual Studio 개발자 서버를 사용하여 실행중인 ASP.NET MVC 사이트입니다./Content 폴더 (이미지, 스크립트, 스타일)에 정적 컨텐츠가 있습니다. Google 페이지 속도는 정적 콘텐츠에 만료가 지정되지 않은 캐싱 b/c를 구현할 것을 제안합니다. 그 문제에 대한ASP.NET MVC의 정적 컨텐트 캐싱 및 압축

<system.webServer> 
<staticContent> 
    <clientCache cacheControlMaxAge="7.00:00:00" cacheControlMode="UseMaxAge"/> 
</staticContent> 
</system.webServer> 

, 나 또한 이러한 파일의 압축을 사용하려면 : 나는이의 web.config에 다음하지만 도움이 보이지 않는다 포함되어 있습니다. 둘 다하는 법을 알고 싶습니다. 감사.

public class CompressAttribute : ActionFilterAttribute 
    { 
     /// <summary> 
     /// Enables compression on page response 
     /// </summary> 
     /// <param name="filterContext">Filter context</param> 
     public override void OnActionExecuting(ActionExecutingContext filterContext) 
     { 
      HttpRequestBase request = filterContext.HttpContext.Request; 

      string acceptEncoding = request.Headers["Accept-Encoding"]; 

      if (string.IsNullOrEmpty(acceptEncoding)) return; 

      acceptEncoding = acceptEncoding.ToUpperInvariant(); 

      HttpResponseBase response = filterContext.HttpContext.Response; 

      if (acceptEncoding.Contains("DEFLATE")) 
      { 
       response.AppendHeader("Content-encoding", "deflate"); 
       response.Filter = new WebCompressionStream(response.Filter, CompressionType.Deflate); 
      } 
      else if (acceptEncoding.Contains("GZIP")) 
      { 
       response.AppendHeader("Content-encoding", "gzip"); 
       response.Filter = new WebCompressionStream(response.Filter, CompressionType.GZip); 
      } 
     } 
    } 

WebCompressionStream 클래스는 다음과 같습니다 : 당신이 그것을 압축을 사용하려는 경우에만 [Compress]와 컨트롤러 방법을 장식 할 수 있도록

+0

압축 : http://stackoverflow.com/questions/6992524/how-do-i-enable-gzip-compression-when-using-mvc3-on-iis7 – Rory

답변

1

가능한 경우 압축을 IIS에 직접 설정하는 것이 가장 좋습니다. 그렇지 않으면 작업 결과 압축에 사용자 지정 특성을 사용하는 것이 널리 퍼져 있습니다.

자바 스크립트, CSS 및 리소스 파일의 경우 Ajax Minifier 같은 도구를 사용할 수 있습니다 (빌드 작업으로 설정할 수도 있음). 모든 자바 스크립트를 포장 또는 CSS를 들어

당신이 그들을 결합하는 컨트롤러 액션을 작성하고 당신의보기에서 전화보다 수있는 파일 등 : 또한

, jQuery와 같은 일반적인 자바 스크립트 라이브러리를 사용하는 경우 CDN 공급자를 사용하는 것을 고려하십시오.

+0

"가능한 경우 IIS에서 최선의 설정"을 선택하면 Windows Azure를 사용하게됩니다. 이미 jsmin.exe로 축소하고 있지만 gzip 형식 압축은 추가 레이어라는 점을 이해합니다. 맞습니까? Ajax Minifier는 JSMin을 축소하고 압축합니까? Azure가 단지 압축을 처리할까요? – Vince

4

압축을 위해, 나는 다음과 같은 사용자 정의 CompressAttribute 클래스를 사용

public sealed class WebCompressionStream : Stream 
    { 
     private readonly Stream _compSink; 
     private readonly Stream _finalSink; 

     /// <summary> 
     /// Initializes a new instance of the <see cref="WebCompressionStream"/> class. 
     /// </summary> 
     /// <param name="stm">The stream</param> 
     /// <param name="comp">The compression type to use</param> 
     public WebCompressionStream(Stream stm, CompressionType comp) 
     { 
      switch (comp) 
      { 
       case CompressionType.Deflate: 
        _compSink = new DeflateStream((_finalSink = stm), CompressionMode.Compress); 
        break; 
       case CompressionType.GZip: 
        _compSink = new GZipStream((_finalSink = stm), CompressionMode.Compress); 
        break; 
       default: 
        throw new ArgumentException(); 
      } 
     } 

     /// <summary> 
     /// Gets the sink. 
     /// </summary> 
     /// <value>The sink.</value> 
     public Stream Sink 
     { 
      get 
      { 
       return _finalSink; 
      } 
     } 

     /// <summary> 
     /// Gets the type of the compression. 
     /// </summary> 
     /// <value>The type of the compression.</value> 
     public CompressionType CompressionType 
     { 
      get 
      { 
       return _compSink is DeflateStream ? CompressionType.Deflate : CompressionType.GZip; 
      } 
     } 

     /// <summary> 
     /// When overridden in a derived class, gets a value indicating whether the current stream supports reading. 
     /// </summary> 
     /// <value></value> 
     /// <returns>true if the stream supports reading; otherwise, false.</returns> 
     public override bool CanRead 
     { 
      get 
      { 
       return false; 
      } 
     } 

     /// <summary> 
     /// When overridden in a derived class, gets a value indicating whether the current stream supports seeking. 
     /// </summary> 
     /// <value></value> 
     /// <returns>true if the stream supports seeking; otherwise, false.</returns> 
     public override bool CanSeek 
     { 
      get 
      { 
       return false; 
      } 
     } 

     /// <summary> 
     /// When overridden in a derived class, gets a value indicating whether the current stream supports writing. 
     /// </summary> 
     /// <value></value> 
     /// <returns>true if the stream supports writing; otherwise, false.</returns> 
     public override bool CanWrite 
     { 
      get 
      { 
       return true; 
      } 
     } 

     /// <summary> 
     /// When overridden in a derived class, gets the length in bytes of the stream. 
     /// </summary> 
     /// <value></value> 
     /// <returns>A long value representing the length of the stream in bytes.</returns> 
     /// <exception cref="T:System.NotSupportedException">A class derived from Stream does not support seeking. </exception> 
     /// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception> 
     public override long Length 
     { 
      get 
      { 
       throw new NotSupportedException(); 
      } 
     } 

     /// <summary> 
     /// When overridden in a derived class, gets or sets the position within the current stream. 
     /// </summary> 
     /// <value></value> 
     /// <returns>The current position within the stream.</returns> 
     /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception> 
     /// <exception cref="T:System.NotSupportedException">The stream does not support seeking. </exception> 
     /// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception> 
     public override long Position 
     { 
      get 
      { 
       throw new NotSupportedException(); 
      } 
      set 
      { 
       throw new NotSupportedException(); 
      } 
     } 

     /// <summary> 
     /// When overridden in a derived class, clears all buffers for this stream and causes any buffered data to be written to the underlying device. 
     /// </summary> 
     /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception> 
     public override void Flush() 
     { 
      //We do not flush the compression stream. At best this does nothing, at worst it 
      //loses a few bytes. We do however flush the underlying stream to send bytes down the 
      //wire. 
      _finalSink.Flush(); 
     } 

     /// <summary> 
     /// When overridden in a derived class, sets the position within the current stream. 
     /// </summary> 
     /// <param name="offset">A byte offset relative to the <paramref name="origin"/> parameter.</param> 
     /// <param name="origin">A value of type <see cref="T:System.IO.SeekOrigin"/> indicating the reference point used to obtain the new position.</param> 
     /// <returns> 
     /// The new position within the current stream. 
     /// </returns> 
     /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception> 
     /// <exception cref="T:System.NotSupportedException">The stream does not support seeking, such as if the stream is constructed from a pipe or console output. </exception> 
     /// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception> 
     public override long Seek(long offset, SeekOrigin origin) 
     { 
      throw new NotSupportedException(); 
     } 

     /// <summary> 
     /// When overridden in a derived class, sets the length of the current stream. 
     /// </summary> 
     /// <param name="value">The desired length of the current stream in bytes.</param> 
     /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception> 
     /// <exception cref="T:System.NotSupportedException">The stream does not support both writing and seeking, such as if the stream is constructed from a pipe or console output. </exception> 
     /// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception> 
     public override void SetLength(long value) 
     { 
      throw new NotSupportedException(); 
     } 

     /// <summary> 
     /// When overridden in a derived class, reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read. 
     /// </summary> 
     /// <param name="buffer">An array of bytes. When this method returns, the buffer contains the specified byte array with the values between <paramref name="offset"/> and (<paramref name="offset"/> + <paramref name="count"/> - 1) replaced by the bytes read from the current source.</param> 
     /// <param name="offset">The zero-based byte offset in <paramref name="buffer"/> at which to begin storing the data read from the current stream.</param> 
     /// <param name="count">The maximum number of bytes to be read from the current stream.</param> 
     /// <returns> 
     /// The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached. 
     /// </returns> 
     /// <exception cref="T:System.ArgumentException">The sum of <paramref name="offset"/> and <paramref name="count"/> is larger than the buffer length. </exception> 
     /// <exception cref="T:System.ArgumentNullException"> 
     ///  <paramref name="buffer"/> is null. </exception> 
     /// <exception cref="T:System.ArgumentOutOfRangeException"> 
     ///  <paramref name="offset"/> or <paramref name="count"/> is negative. </exception> 
     /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception> 
     /// <exception cref="T:System.NotSupportedException">The stream does not support reading. </exception> 
     /// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception> 
     public override int Read(byte[] buffer, int offset, int count) 
     { 
      throw new NotSupportedException(); 
     } 

     /// <summary> 
     /// When overridden in a derived class, writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written. 
     /// </summary> 
     /// <param name="buffer">An array of bytes. This method copies <paramref name="count"/> bytes from <paramref name="buffer"/> to the current stream.</param> 
     /// <param name="offset">The zero-based byte offset in <paramref name="buffer"/> at which to begin copying bytes to the current stream.</param> 
     /// <param name="count">The number of bytes to be written to the current stream.</param> 
     /// <exception cref="T:System.ArgumentException">The sum of <paramref name="offset"/> and <paramref name="count"/> is greater than the buffer length. </exception> 
     /// <exception cref="T:System.ArgumentNullException"> 
     ///  <paramref name="buffer"/> is null. </exception> 
     /// <exception cref="T:System.ArgumentOutOfRangeException"> 
     ///  <paramref name="offset"/> or <paramref name="count"/> is negative. </exception> 
     /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception> 
     /// <exception cref="T:System.NotSupportedException">The stream does not support writing. </exception> 
     /// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception> 
     public override void Write(byte[] buffer, int offset, int count) 
     { 
      _compSink.Write(buffer, offset, count); 
     } 

     /// <summary> 
     /// Writes a byte to the current position in the stream and advances the position within the stream by one byte. 
     /// </summary> 
     /// <param name="value">The byte to write to the stream.</param> 
     /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception> 
     /// <exception cref="T:System.NotSupportedException">The stream does not support writing, or the stream is already closed. </exception> 
     /// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception> 
     public override void WriteByte(byte value) 
     { 
      _compSink.WriteByte(value); 
     } 

     /// <summary> 
     /// Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream. 
     /// </summary> 
     public override void Close() 
     { 
      _compSink.Close(); 
      _finalSink.Close(); 
      base.Close(); 
     } 

     /// <summary> 
     /// Releases the unmanaged resources used by the <see cref="T:System.IO.Stream"/> and optionally releases the managed resources. 
     /// </summary> 
     /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param> 
     protected override void Dispose(bool disposing) 
     { 
      if (disposing) 
      { 
       _compSink.Dispose(); 
       _finalSink.Dispose(); 
      } 
      base.Dispose(disposing); 
     } 
    } 

    /// <summary> 
    /// Specifies the compression type to be used 
    /// </summary> 
    public enum CompressionType 
    { 
     /// <summary> 
     /// Compression will use deflate 
     /// </summary> 
     Deflate, 

     /// <summary> 
     /// Compression will use GZip 
     /// </summary> 
     GZip 
    } 

사용법 :

[Compress] 
public ActionResult SomeView() 
{ 
    return View("SomeView"); 
} 
+0

감사합니다. 방금 찾은 http://weblogs.asp.net/rashid/archive/2008/03/28/asp-net-mvc-action-filter-caching-and-compression.aspx와 비슷한 접근 방식입니다. 문제는 ... aspx 페이지의 html을 압축하지만 여전히 js 또는 css를 압축하지 않습니다. 어떻게 파일을 압축합니까? – Vince

+0

정적 콘텐츠 압축은 기본적으로 IIS에서 처리 할 수 ​​있습니다. web.config에서 키를 사용하십시오. –