如何检查当前请求资源是 C# ASP.NET 中的一个页面? [英] How to check current request resource is a page in C# ASP.NET?

查看:23
本文介绍了如何检查当前请求资源是 C# ASP.NET 中的一个页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an IHttpModule implementation with a delegated method hooked to PostAcquireRequestState, for each HTTP Request, I would like to know how to check if the current requested resource is a Page (aspx) discriminating all other resources like *.css, *.ico, *.png and so on.

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

Actually I can do the following:

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

但我想知道除了使用.aspx"进行硬检查之外,是否还有其他事情要做.

But I would like to know if there is something different to do than hard checking with ".aspx".

推荐答案

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

One thing you could do is to get a list of registered HTTP Handlers and check whether they are handled by a system class. Assuming you don't name your own classes in a namespace System.*, this is quite foolproof:

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);
    }
}

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

Alternatively, you can revert the lookup and list all existing handlers except those in your own (or current) domain, possibly provided some exceptions (i.e., if you want to override an existing image handler). But whatever you choose, this gives you full access to what's already registered.

注意:反过来做通常更容易.您现在似乎想将几条路径列入黑名单,但相反,如果您可以进行白名单(即,列出您要做 想要处理的那些扩展),您可以自己制作很多更容易.

Note: it's generally easier to do the reverse. You now seem to want to blacklist a couple of paths, but instead, if you can do whitelisting (i.e., make a list of those extensions that you do want to handle) you can make it yourself a lot easier.

这篇关于如何检查当前请求资源是 C# ASP.NET 中的一个页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆