7

我有一个 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);
}

这有效并且足够快,但感觉非常笨重。如果我们添加没有想到的新静态文件,特别是依赖扩展将容易出错。

有没有更好的方法而不更改 IIS 配置?

4

3 回答 3

0

毫无疑问,您需要创建自定义扩展方法,因为 ASP.NET 路由引擎使用此代码来决定文件是否存在,

if (!this.RouteExistingFiles)
{
    string appRelativeCurrentExecutionFilePath = httpContext.Request.AppRelativeCurrentExecutionFilePath;
     if (((appRelativeCurrentExecutionFilePath != "~/") && (this._vpp != null)) && (this._vpp.FileExists(appRelativeCurrentExecutionFilePath) || this._vpp.DirectoryExists(appRelativeCurrentExecutionFilePath)))
     {
          return null;
       }
}

您将无法使用 context.handler 在 Application_BeginRequest 中确定请求是否是静态的,因为路由模块可能会更改处理程序,并且此模块始终在 Application_BeginRequest 之后执行。我的建议是使用 ASP.NET 路由引擎使用的类似代码。

于 2011-07-13T12:26:31.137 回答
0

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

在 IIS6 中,只有 .net 文件,例如 aspx 被映射到一个处理程序。

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

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

西蒙

于 2011-07-13T10:13:14.517 回答
0

有几个选项:

  • 为不需要任何身份验证且包含静态文件的路径添加authorization 元素并拒绝无
  • 您正在使用集成管道。在 IIS 7 上将其关闭。
于 2011-07-13T10:20:07.717 回答