Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading AuthorizationSection from web.config provides incorrect values

Edit #2: config.FilePath is showing that it's looking at a different file than what I'm expecting: "C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\web.config". I was expecting it to use the web.config in my project. Need to figure out why that's happening.

I have a method in my web API where I'm trying to read the values from the authorization section in my web.config. Based on what I've found, this should work:

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

And this is the section of the web.config that contains the authorization info:

  <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>

You can see that there is one allow and one deny. When I run the code, it appears that there is only one rule. Shouldn't there be two since there is an allow and a deny? And the one rule looks to have an Action of Allow and "*" for Users. That's not what's in the web.config. What am I missing here?

enter image description here

** Edit ** I've considered the possibility that it's reading a different web.config file. But there is only one other web.config file in the solution (under Views). I also changed it to have the same authorization section, but I still get the same result.

like image 402
Bob Horn Avatar asked Oct 31 '22 00:10

Bob Horn


1 Answers

As you already figured out using Null in for the path parameter of OpenWebConfiguration loads the server root web.config in

%SystemRoot%\Microsoft.NET\Framework64\v4.0.30319\Config\

the documentation says:

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

but one could assume it would be the root web config of the site, not the server. Anyway, try using:

var config = WebConfigurationManager.OpenWebConfiguration("~");
like image 111
Peter Hahndorf Avatar answered Nov 15 '22 04:11

Peter Hahndorf