Eytan Levit
Eytan Levit

Reputation: 473

UrlRewriting on Global.asax and SQL Output Caching

I'm performing a UrlRewrite for my main category pages. Converting:

www.mysite.com/Category.aspx?id=2 

to

www.mysite.com/Dogs

In order to do so I'm using Global.asax's Application_BeginRequest where I perform the following code(pseudocode):

protected void Application_BeginRequest(Object sender, EventArgs e)
{
    if (IsCategoryUrl())
    {
        string CategoryName = ParseCategoryNameFromUrl(Request.Url);
        string CategoryId = GetCategoryIdByNameFromDB( CategoryName );
        Context.RewritePath("/Category.aspx?id=" + CategoryId);
    }
}

My questions are:

  1. Is this the right way to perform Url Rewriting? (It's the first time I'm doing so).
  2. This code causes a read from DB on almost EVERY request, is there any way to cache it? The only technique I found for SQL Caching required a <%@ Page %> directive which isn't possible on the global.asax. Any other solution?

Thanks in advance.

Upvotes: 3

Views: 1208

Answers (1)

Ray Booysen
Ray Booysen

Reputation: 30021

There is nothing wrong with caching your database queries. For every category name you can store the ID in a dictionary as an example that expire after a certain period of time. This will remove the DB calls in this case. As an example:

Dictionary<string, int> categoryIdLookup;

This can be stored in the HTTP cache and retrieved, if it is null (I.e. it has never been added or has fallen out of cache) build the dictionary, lookup the correct Id and then do the rewrite.

Upvotes: 2

Related Questions