Skip to content
标签
欢迎扫码关注公众号

ASP.NET 静态文件如何添加令牌

在 ASP.NET 中通过实现 IHttpHandler 接口来拦截静态文件请求。

示例代码

Web.config

xml
<?xml version="1.0" encoding="utf-8"?>
<!--
  有关如何配置 ASP.NET 应用程序的详细信息,请访问
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <system.webServer>
    <handlers>
      <add name="html" path="*.html" verb="*" type="StatisFileFilter.StaticFileHandler" />
    </handlers>
  </system.webServer>
</configuration>

StaticFileHandler.cs

csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace StatisFileFilter
{
    public class StaticFileHandler : IHttpHandler
    {
        public bool IsReusable
        {
            get
            {
                return true;
            }
        }

        public void ProcessRequest(HttpContext context)
        {
            context.Response.Headers.Set("Token", Guid.NewGuid().ToString());
            context.Response.WriteFile(context.Request.PhysicalPath);
        }
    }
}

性能测试

测试用的 3 个页面仅显示 Hello World,没有其他任何处理。
其中 .htm 后缀的静态文件不会被拦截,.html 后缀的文件会被拦截。
使用 JMeter 设置 5 个线程,每个线程 100 个请求来测试性能。
测试结果如下:

Label样本平均值最小值最大值
HelloWorld.aspx50017028434
HelloWorld.html500545266
HelloWorld.htm5004129
  • HelloWorld.htm 没有被拦截,效率最高,平均响应时间为 4ms;
  • HelloWorld.html 被拦截后性能急剧下降,响应时间是静态文件的 10 多倍;
  • HelloWorld.aspx 最慢,响应时间是被拦截的静态文件的 3 倍;

参考

  1. 要在 asp.net 处理静态资源时,Web.Config 配置方式
  2. asp.net 用 httpmodule 能拦截.html 后缀的请求么
  3. IHttpHandler.IsReusable Property
  4. What is the use for IHttpHandler.IsReusable?

Page Layout Max Width

Adjust the exact value of the page width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the page layout
A ranged slider for user to choose and customize their desired width of the maximum width of the page layout can go.

Content Layout Max Width

Adjust the exact value of the document content width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the content layout
A ranged slider for user to choose and customize their desired width of the maximum width of the content layout can go.