【问题标题】:Exception on accessing a class in Web API访问 Web API 中的类时出现异常
【发布时间】:2016-09-13 22:39:41
【问题描述】:

我遇到了一个奇怪的行为。由于这个异常,我的 Web API 突然无法使用:

[ArgumentNullException: Value cannot be null.
Parameter name: String]
   System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal) +14198596
   System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) +177
   Dota2IoT.Server.Models.ViewModels.NatMappingManager..cctor() +112

[TypeInitializationException: The type initializer for 'Dota2IoT.Server.Models.ViewModels.NatMappingManager' threw an exception.]
   Dota2IoT.Server.MvcApplication.Application_Start() +223

这是NapMappingManager的构造函数:

    private ConcurrentDictionary<int, NatMappingViewModel> mappings;

    private NatMappingManager()
    {
        this.mappings = new ConcurrentDictionary<int, NatMappingViewModel>();
    }

以前,我什至没有从 Global.asax Application_Start 调用 NapMappingManager,但我认为这可能是因为一些并发。但是,现在我尝试调用:

// Initialize the NAT
Models.ViewModels.NatMappingManager.Instance.ToString()

所以可以调用构造函数,但是会发生同样的错误。它出什么问题了?我对代码做了什么,还是来自ConcurrentDictionary 的错误?

编辑:我的本地机器上没有发生异常。它只发生在我的 Azure VM (Window Server 2012) 服务器上。

编辑以澄清正确答案:

这是导致问题的代码(我没有显式的静态构造函数):

    private static readonly int MaxDeviceNumber = int.Parse(ConfigurationManager.AppSettings["MaxDeviceNumber"]);
    private static readonly int MinDeviceNumber = int.Parse(ConfigurationManager.AppSettings["MinDeviceNumber"]);

【问题讨论】:

    标签: c# dictionary concurrency asp.net-web-api2 concurrentdictionary


    【解决方案1】:

    .cctorstatic 构造函数。这符合您有类型初始化程序异常的事实。看起来您正试图在 NatMappingManager 的静态构造函数中解析 int,但您传递给它的值是 null

    (如果您没有显式的静态构造函数,请在声明的同一行查找正在初始化的静态成员。)

    【讨论】:

    • 正确!我错过了一些应该存在的设置值。非常感谢,15分钟后接受答复。我还将标题更改为更清晰。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-25
    • 1970-01-01
    相关资源
    最近更新 更多