简体   繁体   中英

Microsoft.Web.Administration - NullReferenceException with httpErrors in ApplicationHost.Config

I am trying to figure out why I am getting a NullReferenceException with the following code. Everything seems to look like it is nested properly. I am using Microsoft.Web.Administration and I am attempting to modify the prefixLanguageFilePath for all the errors. Any help would be appreciated!

    public static void ModifyCustomErrDir(string dir)
    {
        try
        {
            ServerManager serverManager = new ServerManager();
            Configuration config = serverManager.GetApplicationHostConfiguration();

            config.GetSection("system.webServer/httpErrors").ChildElements["error"].Attributes["prefixLanguageFilePath"].Value = dir;
        }
        catch (ServerManagerException e)
        {
            Console.WriteLine(e);
        }
    }

    <httpErrors lockAttributes="allowAbsolutePathsWhenDelegated,defaultPath">
        <error statusCode="401" prefixLanguageFilePath="%SystemDrive%\inetpub\custerr" path="401.htm" />
        <error statusCode="403" prefixLanguageFilePath="%SystemDrive%\inetpub\custerr" path="403.htm" />
        <error statusCode="404" prefixLanguageFilePath="%SystemDrive%\inetpub\custerr" path="404.htm" />
        <error statusCode="405" prefixLanguageFilePath="%SystemDrive%\inetpub\custerr" path="405.htm" />
        <error statusCode="406" prefixLanguageFilePath="%SystemDrive%\inetpub\custerr" path="406.htm" />
        <error statusCode="412" prefixLanguageFilePath="%SystemDrive%\inetpub\custerr" path="412.htm" />
        <error statusCode="500" prefixLanguageFilePath="%SystemDrive%\inetpub\custerr" path="500.htm" />
        <error statusCode="501" prefixLanguageFilePath="%SystemDrive%\inetpub\custerr" path="501.htm" />
        <error statusCode="502" prefixLanguageFilePath="%SystemDrive%\inetpub\custerr" path="502.htm" />
    </httpErrors>

Edit:

I got it working by looping through the collection without denoting the error tag and just looking for the attribute. I will have to come back to it to see if there would be any unintended adverse "features" by doing it this way.

var httpErrorsCollection = config.GetSection("system.webServer/httpErrors")
       .GetCollection(); 

foreach (var error in httpErrorsCollection) 
    error.Attributes["prefixLanguageFilePath"].Value = dir;
//config.GetSection("system.webServer/httpErrors").ChildElements["error"].
//        Attributes["prefixLanguageFilePath"].Value = dir;

var errorSection = config.GetSection("system.webServer/httpErrors");
// check errorSection    
var errors = errorSection.ChildElements["error"];
// check errors
errors.Attributes["prefixLanguageFilePath"].Value = dir;

etc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM