Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6973331
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T17:05:40+00:00 2026-05-27T17:05:40+00:00

I am writing a http handler that will load a file (css template) modify

  • 0

I am writing a http handler that will load a file (css template) modify it’s contents and serve it up as text/css.

I am basing the code on an example I found here:

http://madskristensen.net/post/Remove-whitespace-from-stylesheets-and-JavaScript-files.aspx

The business part of the code is:

public void ProcessRequest(HttpContext context)
{
    try
    {
        string file = context.Request.PhysicalPath;
        if (!File.Exists(file))
            return;

        string body = string.Empty;

        if (context.Cache[CSS_CACHE_BODY + file] != null)
            body = context.Cache[CSS_CACHE_BODY + file].ToString();

       if (body == string.Empty)
        {
            StreamReader reader = new StreamReader(file);
            body = reader.ReadToEnd();
            reader.Close();

            // Modify css template here
            CacheDependency cd = new CacheDependency(file);

            context.Cache.Insert(CSS_CACHE_BODY + file, body, cd);
        }

        context.Response.ContentType = "text/css";
        context.Response.Write(body);
    }
    catch (Exception ex)
    {
        context.Response.Write(ex.Message);
    }
}

I would appreciate if people could comment on the efficency and robustness of this code. I would rather not wait until it is a production environment to find out any problems!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T17:05:41+00:00Added an answer on May 27, 2026 at 5:05 pm

    There are some performance tips, you can cache the response client-side (using HTTP Headers). Andalso before sending the response, you can use White Space Removal method for your output. Another point is compression: compress the reponse if the browser support it.

    Sample of client-side caching (in VB):

            Dim incomingEtag As String = context.Request.Headers("If-None-Match")
            Dim freshness As New TimeSpan(100, 0, 0, 0)
            context.Response.Cache.SetCacheability(HttpCacheability.Public)
            context.Response.Cache.SetExpires(DateTime.Now.ToUniversalTime.Add(freshness))
            context.Response.Cache.SetMaxAge(freshness)
            context.Response.Cache.SetValidUntilExpires(True)
            context.Response.Cache.VaryByHeaders("Accept-Encoding") = True
            context.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches)
    
            Dim outgoingEtag As String = context.Request.Url.Authority & context.Request.Url.Query.GetHashCode()
            context.Response.Cache.SetETag(outgoingEtag)
    

    Sample of White Space Removel function for CSS:

        Private Function StripWhitespace(ByVal body As String) As String
    
            body = body.Replace("  ", " ")
            body = body.Replace(Environment.NewLine, [String].Empty)
            body = body.Replace(vbTab, String.Empty)
            body = body.Replace(" {", "{")
            body = body.Replace(" :", ":")
            body = body.Replace(": ", ":")
            body = body.Replace(", ", ",")
            body = body.Replace("; ", ";")
            body = body.Replace(";}", "}")
    
            ' sometimes found when retrieving CSS remotely
            body = body.Replace("?", String.Empty)
    
            'body = Regex.Replace(body, @"/\*[^\*]*\*+([^/\*]*\*+)*/", "$1");
            body = Regex.Replace(body, "(?<=[>])\s{2,}(?=[<])|(?<=[>])\s{2,}(?=&nbsp;)|(?<=&ndsp;)\s{2,}(?=[<])", [String].Empty)
    
            'Remove comments from CSS
            body = Regex.Replace(body, "/\*[\d\D]*?\*/", String.Empty)
    
            Return body
    
        End Function
    

    Sample of White Space Removel function for JS:

        Private Function StripWhitespace(ByVal body As String) As String
    
            Dim lines As String() = body.Split(New String() {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
            Dim emptyLines As New StringBuilder()
            For Each line As String In lines
                Dim s As String = line.Trim()
                If s.Length > 0 AndAlso Not s.StartsWith("//") Then
                    emptyLines.AppendLine(s.Trim())
                End If
            Next
    
            body = emptyLines.ToString()
            body = Regex.Replace(body, "^[\s]+|[ \f\r\t\v]+$", [String].Empty)
            body = Regex.Replace(body, "([+-])\n\1", "$1 $1")
            body = Regex.Replace(body, "([^+-][+-])\n", "$1")
            body = Regex.Replace(body, "([^+]) ?(\+)", "$1$2")
            body = Regex.Replace(body, "(\+) ?([^+])", "$1$2")
            body = Regex.Replace(body, "([^-]) ?(\-)", "$1$2")
            body = Regex.Replace(body, "(\-) ?([^-])", "$1$2")
            body = Regex.Replace(body, "\n([{}()[\],<>/*%&|^!~?:=.;+-])", "$1")
            body = Regex.Replace(body, "(\W(if|while|for)\([^{]*?\))\n", "$1")
            body = Regex.Replace(body, "(\W(if|while|for)\([^{]*?\))((if|while|for)\([^{]*?\))\n", "$1$3")
            body = Regex.Replace(body, "([;}]else)\n", "$1 ")
            body = Regex.Replace(body, "(?<=[>])\s{2,}(?=[<])|(?<=[>])\s{2,}(?=&nbsp;)|(?<=&ndsp;)\s{2,}(?=[<])", [String].Empty)
    
            Return body
    
        End Function
    

    Here is a sample to compress the output:

            Dim request As HttpRequest = context.Request
            Dim response As HttpResponse = context.Response
    
            Dim browserAcceptedEncoding As String = request.Headers("Accept-Encoding")
    
            If Not String.IsNullOrEmpty(browserAcceptedEncoding) Then
    
                browserAcceptedEncoding = browserAcceptedEncoding.ToLowerInvariant
    
                If (browserAcceptedEncoding.Contains("gzip")) Then
                    response.AppendHeader("Content-encoding", "gzip")
                    response.Filter = New GZipStream(response.Filter, CompressionMode.Compress)
    
                ElseIf (browserAcceptedEncoding.Contains("deflate")) Then
                    response.AppendHeader("Content-encoding", "deflate")
                    response.Filter = New DeflateStream(response.Filter, CompressionMode.Compress)
    
                End If
    
            End If
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am writing http server that can serve big files to client. While writing
I'm writing a multi-tenant app that will receive requests like http://www.tenant1.com/content/images/logo.gif and http://www.anothertenant.com/content/images/logo.gif .
I'm writing a getSitemapR handler that uses yesod-sitemap to generate a sitemap file. The
I'm writing http session manager (gen_server based). That server creates and removes session from
I'm writing a Java application that will run for a long time (essentially, it
Writing an app that will include the ability to decompress zip and rar files.
I'm writing an MVC3 application that will need to make use of URL rewriting
I am writing an add-on for Windows Picture viewer that will need to send
I'm writing a simple reverse proxy which will need to handle http GETs and
I am interested in writing an application that will take in an excel document

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.