在Application_BeginRequest期间检查静态文件?

Kei*_*ith 6 asp.net asp.net-mvc static-files global-asax

我有一个Global.asx文件,需要进行自定义身份验证,审核和分析.这是必需的,因为它支持基于SAML的SSO系统,需要覆盖正常的.Net身份验证(不支持SAML或混合身份验证)

我不想启动它的静态文件,如.js,.css,.png,等

在Cassini/WebDev和IIS7中确实如此.

我想要的是一些简单的检查,比如this.Request.IsStaticFile(不幸的是,它不存在)来识别静态文件.

我意识到编写它会相当简单,但感觉就像已经存在的东西 - IIS已经为静态文件应用了缓存策略等等.

我需要一个代码解决方案,而不是IIS配置更改一个.

更新

这是我目前的解决方法:

/// <summary>Hold all the extensions we treat as static</summary>
static HashSet<string> allowedExtensions = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
    ".js", ".css", ".png", ...
};

/// <summary>Is this a request for a static file?</summary>
/// <param name="request">The HTTP request instance to extend.</param>
/// <returns>True if the request is for a static file on disk, false otherwise.</returns>
public static bool IsStaticFile(this HttpRequest request)
{
    string fileOnDisk = request.PhysicalPath;
    if (string.IsNullOrEmpty(fileOnDisk))
    {
        return false;
    }

    string extension = Path.GetExtension(fileOnDisk);

    return allowedExtensions.Contains(extension);
}
Run Code Online (Sandbox Code Playgroud)

这很有效,而且速度很快,但感觉非常笨重.特别是如果我们添加未考虑的新静态文件,那么依赖于扩展将容易出错.

有没有更好的IIS配置更好的方法?

Sim*_*sey 0

您也许可以检查哪个处理程序正在处理该请求。

在 IIS6 中,只有 .net 文件(例如 aspx)被映射到执行某些操作的处理程序。

在具有集成管道的 IIS7 中,所有内容都通过 .net 路由,这通常是一件好事。不过,不同的处理程序仍然处理不同的文件类型。我特别相信 staticfilehandler 是您需要检查的一个。该httpcontext.handler属性应该可以让您弄清楚。

您可以创建一个扩展方法来添加 IsStatic 方法...

西蒙