Cấp bậc tác giả:

DOTNET

Hướng dẫn bật nén Gzip cho website Asp.Net

Được viết bởi webmaster ngày 26/10/2015 lúc 05:09 PM
Ở bài trước, tôi đã giới thiệu về cách tối ưu hóa Html,Css & Javascript để giảm dung lượng và tăng tốc độ tải của website, ở bài này chúng ta sẽ tìm hiểu về tính năng nén Gzip hiện tại đang được áp dụng rất phổ biến và được cho là tối ưu nhất. Gzipping giảm thời gian đáp ứng các yêu cầu của client bằng cách nén các thông tin trả lời và giảm đươc 70% kích thước.
  • 0
  • 8925

Hướng dẫn bật nén Gzip cho website Asp.Net

Ở bài trước, tôi đã giới thiệu về cách tối ưu hóa Html,Css & Javascript để giảm dung lượng và tăng tốc độ tải của website, ở bài này chúng ta sẽ tìm hiểu về tính năng nén Gzip hiện tại đang được áp dụng rất phổ biến và được cho là tối ưu nhất. Gzipping giảm thời gian đáp ứng các yêu cầu của client bằng cách nén các thông tin trả lời và giảm đươc 70% kích thước. Hầu hết 90% các giao tiếp trên Internet giữa các trình duyệt và máy chủ web đều sử dụng Gzip.

Đối với các website viết bằng php sử dụng Sever Apache việc áp dụng sẽ khác, ở đây ta chỉ tìm hiểu cách áp dụng gzip thế nào đối với một website Asp.net

1. Sử dụng Gzip
- Để sử dụng Gzip, trong file Global.asax chúng ta cần thêm một số đoạn mã code dưới đây:

protected void Application_BeginRequest(object sender, EventArgs e)
    {
        HttpApplication app = (HttpApplication)sender;
        string acceptEncoding = app.Request.Headers["Accept-Encoding"];
        System.IO.Stream prevUncompressedStream = app.Response.Filter;
 
        if (acceptEncoding == null || acceptEncoding.Length == 0)
            return;
 
        acceptEncoding = acceptEncoding.ToLower();
 
        if (acceptEncoding.Contains("gzip"))
        {
            // gzip
            app.Response.Filter = new System.IO.Compression.GZipStream(prevUncompressedStream,
                System.IO.Compression.CompressionMode.Compress);
            app.Response.AppendHeader("Content-Encoding",
                "gzip");
        }
        else if (acceptEncoding.Contains("deflate"))
        {
            // defalte
            app.Response.Filter = new System.IO.Compression.DeflateStream(prevUncompressedStream,
                System.IO.Compression.CompressionMode.Compress);
            app.Response.AppendHeader("Content-Encoding",
                "deflate");
        }
    }
HTTP_request_compressed.png

2. Sử dụng Gzip cách 2.
Sở dĩ tôi muốn nói thêm về một cách sử dụng nữa vì đối với phương pháp trên ở một số website có thể xẩy ra lỗi javascript, và tôi chưa tìm được biện pháp khắc phục ^.^... và đây là biện pháp tôi sử dụng để thay thế và có hiệu quả.

- Đầu tiên trong thư mục App_Code các bạn tạo thêm một class có tên GlobalGZip.cs với nội dung như sau
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.IO.Compression;
 
/// <summary>
/// Summary description for GlobalGZip
/// </summary>
public class GlobalGZip : System.Web.HttpApplication
{
    public GlobalGZip()
    {
        InitializeComponent();
    }
 
    private void InitializeComponent()
    {
        this.PostReleaseRequestState += new EventHandler(Global_PostReleaseRequestState);
    }
 
    /// <summary>
    /// Event handler for PostReleaseRequestState
    /// </summary>
    private void Global_PostReleaseRequestState(object sender, EventArgs e)
    {
        string contentType = Response.ContentType; // Get the content type.
 
        // Compress only html and stylesheet documents.
        if (contentType == "text/html" || contentType == "text/css")
        {
            // Get the Accept-Encoding header value to know whether zipping is supported by the browser or not.
            string acceptEncoding = Request.Headers["Accept-Encoding"];
 
            if (!string.IsNullOrEmpty(acceptEncoding))
            {
                // If gzip is supported then gzip it else if deflate compression is supported then compress in that technique.
                if (acceptEncoding.Contains("gzip"))
                {
                    // Compress and set Content-Encoding header for the browser to indicate that the document is zipped.
                    Response.Filter = new GZipStream(Response.Filter, CompressionMode.Compress);
                    Response.AppendHeader("Content-Encoding", "gzip");
                }
                else if (acceptEncoding.Contains("deflate"))
                {
                    // Compress and set Content-Encoding header for the browser to indicate that the document is zipped.
                    Response.Filter = new DeflateStream(Response.Filter, CompressionMode.Compress);
                    Response.AppendHeader("Content-Encoding", "deflate");
                }
            }
        }
    }
}

- Tiếp theo ta chỉ cần chỉnh sửa lại một chút ở file Global.asax của chúng ta như sau, đó là Inherits lớp chúng ta mới tạo vào (Chú ý bỏ hàm Gzip trước đó chúng ta đã thêm vào ở phương pháp 1)
<%@ Application Language="C#" Inherits="GlobalGZip"%>

3. Kiểm tra tính năng Gzip của website
Sau khi tiến hành tích hợp tính năng Gzip vào website, chúng ta có thể sử dụng một số công cụ sau để kiểm tra

sau-khi-nen-gzip.jpg

Nguồn bài viết: DOTNET.VN

BÌNH LUẬN BÀI VIẾT

Bài viết mới nhất

LIKE BOX

Bài viết được xem nhiều nhất

HỌC HTML