Monday, April 9, 2012

Rewrite Url, thật đơn giản!

Kỹ thuật rewrite URL là kỹ thuật dùng để che giấu url thật nhằm chống lại khả năng tấn công vào url.

Ví dụ: thật sự bạn cần đưa ra 1 url như sau:
(1) http://www.banhang.com?product.aspx?productID=123&ProductType=Hardware

nhưng thực tế trên thanh địa chỉ của trình duyệt thì phải là:
(2) http://www.banhang.com/Product/Hardware/123 chẳng hạn.

Lúc này RewiteURL đã làm cái việc chuyển đổi (2) -> (1) theo một quy tắc người lập trình quy định.

Ví dụ dưới kèm theo sẽ minh họa cách rewrite những Url aspx thành aspvn

Cách bước thực hiện như sau:

  1. Tạo 1 class có tên là RewriteUrlClass thừa kế từ IHttpModule:

using System;

using System.Web;

 

public class RewriteUrlClass : IHttpModule

{

    #region IHttpModule Members

 

    public void Dispose()

    {

    }

 

    public void Init(HttpApplication context)

    {

        context.BeginRequest += Context_BeginRequest;

    }

 

    private static void Context_BeginRequest(object sender, EventArgs e)

    {

        HttpApplication httpApplication = (HttpApplication) sender;

        string url = httpApplication.Request.RawUrl.ToLower();

 

        // Nếu là Url ảo như sau"

        if (url.Contains("/default.aspvn"))

        {

            // Thì Url thực mà Server cần xử lý là:

            httpApplication.Context.RewritePath("Default.aspx");

        }

 

        // Nếu là Url ảo như sau"

        if (url.Contains("/login.aspvn"))

        {

            // Thì Url thực mà Server cần xử lý là:

            httpApplication.Context.RewritePath("Login.aspx");

        }

 

        // Tùy thuộc vào quy tắt Rewrite mà chúng ta xử lý.

        // Một trong những cách hiệu quả nhất là dùng Regex Expression.

 

    }

 

   

No comments:

Post a Comment