asp.net http 处理程序和动态 css 生成

发布于 2024-12-22 14:51:53 字数 1260 浏览 2 评论 0原文

我正在编写一个 http 处理程序,它将加载一个文件(css 模板),修改其内容并将其作为文本/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);
    }
}

如果人们可以评论效率和这段代码的鲁棒性。我宁愿不要等到生产环境才发现有问题!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

薄暮涼年 2024-12-29 14:51:53

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

客户端缓存示例(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 的空白删除函数示例

    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,}(?= )|(?<=&ndsp;)\s{2,}(?=[<])", [String].Empty)

        'Remove comments from CSS
        body = Regex.Replace(body, "/\*[\d\D]*?\*/", String.Empty)

        Return body

    End Function

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,}(?= )|(?<=&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

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,}(?= )|(?<=&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,}(?= )|(?<=&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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文