2

我试图弄清楚为什么我会得到NullReferenceException以下代码。一切看起来都像是正确嵌套的。我正在使用Microsoft.Web.Administration并且正在尝试修改所有错误的 prefixLanguageFilePath。任何帮助,将不胜感激!

    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>

编辑:

我通过循环遍历集合而不表示错误标记并仅查找属性来使其工作。我将不得不回到它,看看这样做是否会有任何意想不到的不利“特征”。

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

foreach (var error in httpErrorsCollection) 
    error.Attributes["prefixLanguageFilePath"].Value = dir;
4

1 回答 1

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

于 2012-09-06T20:09:43.643 回答