从 web.config 读取 AuthorizationSection 提供了不正确的值

Reading AuthorizationSection from web.config provides incorrect values

编辑 #2:config.FilePath 显示它查看的文件与我预期的不同:"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\web.config"。我期待它在我的项目中使用 web.config 。需要弄清楚为什么会这样。

我的网站 API 中有一个方法,我试图从我的 web.config 中的授权部分读取值。根据我的发现,这应该可行:

    public AuthorizationSetting GetAuthorizationSettings()
    {
        var config = WebConfigurationManager.OpenWebConfiguration(null);
        var section = config.GetSection("system.web/authorization") as AuthorizationSection;

        foreach (AuthorizationRule rule in section.Rules)
        {
            if (rule.Action.ToString().ToLower() == "allow")
            {
                Debug.WriteLine(rule);
            }
        }

        return new AuthorizationSetting();
    }

这是 web.config 中包含授权信息的部分:

  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
    <identity impersonate="true" />
    <authentication mode="Windows" />
    <authorization>
      <allow roles="role1,role2,role3"/>
      <deny users="*"/>
    </authorization>
  </system.web>

可以看到一允许一拒绝。当我 运行 代码时,似乎只有一个规则。既然有允许和拒绝,难道不应该有两个吗?一条规则看起来对用户具有允许操作和“*”。那不是 web.config 中的内容。我在这里错过了什么?

** 编辑 ** 我考虑过它正在读取另一个 web.config 文件的可能性。但是解决方案中(在视图下)只有一个 web.config 文件。我也将其更改为具有相同的授权部分,但我仍然得到相同的结果。

正如您已经知道的那样,在 OpenWebConfigurationpath 参数中使用 Null 会在

中加载服务器根目录 web.config
%SystemRoot%\Microsoft.NET\Framework64\v4.0.30319\Config\

文档说:

The virtual path to the configuration file. If null, the root Web.config file is opened.

但可以假设它是站点的根 Web 配置,而不是服务器。无论如何,尝试使用:

var config = WebConfigurationManager.OpenWebConfiguration("~");