asp.net http hander和动态css生成

时间:2011-12-20 14:36:04

标签: c# asp.net .net httphandler

我正在编写一个http处理程序,它将加载一个文件(css模板)修改它的内容并将其作为text / css提供。

我的代码基于我在这里找到的一个例子:

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

代码的业务部分是:

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);
    }
}

如果人们可以对此代码的效率和稳健性发表评论,我将不胜感激。我宁愿不要等到它是一个生产环境才能发现任何问题!

1 个答案:

答案 0 :(得分:2)

有一些性能提示,您可以缓存响应客户端(使用HTTP标头)。 Andalso在发送响应之前,您可以使用White Space Removal方法输出。另一点是压缩:如果浏览器支持,则压缩响应。

客户端缓存示例(在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)

CSS的 White Space Removel功能的示例:

    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

JS的 White Space Removel功能的示例:

    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

以下是压缩输出的示例:

        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