输入初始化程序

时间:2012-02-29 05:34:09

标签: c#

我有一个配置类:

namespace SomeCompanyName.SomeAppName
{
    public static class MyConfigClass
    {
        public static readonly string ConsKey = Config.GetAppConfigSetting("ConsKey");
        public static readonly string ConsSecret = Config.GetAppConfigSetting("ConsSecret");
     }
}

我有一种方法试图在字典中使用其中的一些值:

public HttpWebResponse SomeMethod(....)
{

    Dictionary<string, string> headerParams = new Dictionary<string, string> {
        {Constants.Cons, MyConfigClass.ConsumerKey},
        {Constants.Token, MyConfigClass.SingleAccessToken},
        {Constants.ignatureMethod, Constants.SignatureMethodTypeHMACSHA1},
        {Constants.Timestamp, HttpUtility.GenerateTimeStamp()
    };
}

出于某种原因,我收到了这个错误:

  

“'SomeAppConfig'的类型初始值设定项引发了异常。”

无法弄清楚为什么SomeAppConfig类是静态的。

更新:

以下是GetAppConfigSetting的定义:

public class Config
{
    public static string GetAppConfigSetting(string configKey)
    {
        return ConfigurationManager.AppSettings[configKey] ?? string.Empty;
    }
}

更新:

这是我的测试项目中的app.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>

  <appSettings>
    <add key="ConsKey" value="HHGRT6jV4M" />
    <add key="ConsSecret" value="QR47dbduycAc" />
  </appSettings>

</configuration>

3 个答案:

答案 0 :(得分:3)

静态类的类型初始值设定项是设置其静态变量值的代码。在您的情况下,这是代码:

public static readonly string ConsKey = Config.GetAppConfigSetting("ConsKey");
public static readonly string ConsSecret = Config.GetAppConfigSetting("ConsSecret");

确保GetAppConfigSetting可以毫无问题地访问ConsKeyConsSecret。初始化程序抛出的异常应该有更多信息可以帮助您调试问题。

答案 1 :(得分:2)

这意味着静态构造函数中存在异常。在这种情况下,您的属性初始值设定项。也许您寻找的配置密钥不存在。

答案 2 :(得分:0)

你的代码中有拼写错误

Constants.ignatureMethod, Constants.SignatureMethodTypeHMACSHA1}

应该是

Constants.SignatureMethod, Constants.SignatureMethodTypeHMACSHA1}