如何检查当前请求资源是C#ASP.NET中的一个页面?

Rub*_*zzo 10 c# asp.net webforms

我有一个IHttpModule与钩在委托的方法实现PostAcquireRequestState,对于每一个HTTP请求,我想知道如何检查当前请求的资源是一个页面(ASPX)区分所有其他资源,如*.css,*.ico,*.png等等.

其实我可以做到以下几点:

private static void OnPostAcquireRequestState(object sender, EventArgs e)
{
  bool isPage = HttpContext.Current.Request.Path.EndsWith(".aspx");
}
Run Code Online (Sandbox Code Playgroud)

但我想知道是否有不同的事情要做,而不是用".aspx"进行硬盘检查.

Abe*_*bel 3

您可以做的一件事是获取已注册的HTTP 处理程序的列表,并检查它们是否由系统类处理。假设您没有在名称空间中命名自己的类System.*,那么这是非常万无一失的:

using System.Configuration;
using System.Web.Configuration;

Configuration config = WebConfigurationManager.OpenWebConfiguration("/");
HttpHandlersSection handlers = (HttpHandlersSection) config
                               .GetSection("system.web/httpHandlers");

List<string> forbiddenList = new List<string>();

// next part untested:
foreach(HttpHandlerAction handler in handlers.Handlers)
{
    if(handler.Type.StartsWith("System."))
    {
        forbiddenList.Add(handler.Path);
    }
}
Run Code Online (Sandbox Code Playgroud)

或者,您可以恢复查找并列出除您自己(或当前)域中的处理程序之外的所有现有处理程序,可能会提供一些例外(即,如果您想覆盖现有图像处理程序)。但无论您选择什么,这都可以让您完全访问已注册的内容。


注意:通常相反的做法更容易。您现在似乎想要将几个路径列入黑名单,但相反,如果您可以将其列入白名单(即列出您确实想要处理的扩展名),您就可以让自己变得更容易。