c# - Microsoft.Web.Administration - NullReferenceException 与 ApplicationHost.Config 中的 httpErrors

标签 c# iis

我试图弄清楚为什么我使用以下代码得到 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;

最佳答案

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

等等

关于c# - Microsoft.Web.Administration - NullReferenceException 与 ApplicationHost.Config 中的 httpErrors,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12307576/

相关文章:

c# - 在 C# 中将字符串转换为泛型类型(基本或数组)

c# - ASP.NET 将列添加到 Gridview

c# - 基于属性值创建动态 Linq 查询

asp.net - 无法允许用户在 ASP.NET 4.0 应用程序上上传文件

iis - 如何运行 PowerShell 脚本 "in"IIS?

asp.net-mvc - 排除特定目录上的 Web 配置处理程序

iis - ASP.NET Core 2.2(发布版)产生错误并停止 w3wp

c# - Azure Function V2 服务总线消息延迟

javascript - 带有 IFormCollection 的 ViewModel 无法使用错误 500 - ASP.NET Core

asp.net - 如何将新的 Web 应用程序部署到 IIS 站点的子目录,而不必单击 "Convert To Application"?