You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否在Custom.Handler类中获取web.config里add元素的name属性值?

如何在Custom.Handler中获取web.config handlers配置的name属性值

完全可行,你可以通过读取配置节的方式,在Custom.Handler类中定位到对应的handlers配置项并获取其name属性值。

实现方案一:使用Microsoft.Web.Administration(IIS配置管理)

  1. 先给项目添加对Microsoft.Web.Administration程序集的引用(该程序集通常位于C:\Windows\System32\inetsrv目录下)
  2. 在Handler的处理方法中读取当前站点配置,匹配自身类型后获取name值:
using Microsoft.Web.Administration;
using System.Linq;
using System.Web;

public class CustomHandler : IHttpHandler
{
    public bool IsReusable => false;

    public void ProcessRequest(HttpContext context)
    {
        using (ServerManager serverManager = new ServerManager())
        {
            // 获取当前请求对应的站点
            Site currentSite = serverManager.Sites.FirstOrDefault(s => s.Name == context.Request.ServerVariables["SERVER_NAME"]);
            if (currentSite == null) return;

            Configuration config = currentSite.GetWebConfiguration();
            ConfigurationSection handlersSection = config.GetSection("system.webServer/handlers");
            ConfigurationElementCollection handlers = handlersSection.GetCollection();

            // 遍历找到与当前Handler类型匹配的配置项
            foreach (ConfigurationElement handler in handlers)
            {
                string configType = handler["type"]?.ToString();
                if (configType == typeof(CustomHandler).AssemblyQualifiedName)
                {
                    string handlerName = handler["name"]?.ToString();
                    // 此处已获取到目标name值(示例中为"target")
                    context.Response.Write($"当前Handler配置的name值:{handlerName}");
                    break;
                }
            }
        }
    }
}

实现方案二:使用WebConfigurationManager(无需额外引用)

如果不想依赖IIS管理程序集,可直接读取web.config文件:

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

public class CustomHandler : IHttpHandler
{
    public bool IsReusable => false;

    public void ProcessRequest(HttpContext context)
    {
        Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
        ConfigurationSection handlersSection = config.GetSection("system.webServer/handlers");
        ConfigurationElementCollection handlers = handlersSection.GetCollection();

        foreach (ConfigurationElement handler in handlers)
        {
            // 注意替换为你的Handler完整类型名(命名空间+类名+程序集名)
            if (handler["type"]?.ToString().Equals("Custom.Handler, YourAssemblyName", System.StringComparison.OrdinalIgnoreCase) == true)
            {
                string handlerName = handler["name"]?.ToString();
                context.Response.Write($"当前Handler配置的name值:{handlerName}");
                break;
            }
        }
    }
}

注:方案二中的YourAssemblyName需要替换为你的项目编译后的程序集名称(不含.dll后缀)

内容的提问来源于stack exchange,提问作者Andrej B.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 23:36:21