给定的密​​钥不在字典中

时间:2013-08-27 05:58:49

标签: c#

我继承了一个项目,在尝试检索.Net 4.0项目中丢失的密码时,会向用户提供上述错误。我走过去找到了麻烦点,但问题是,生成的值似乎正确,所以我不知道错误发生的原因。提前感谢任何能够查看以下代码并帮助我找到解决方法的人。如果需要更多信息,请与我们联系。我查看了我能找到的所有内容,但没有给我任何可以使用的线索。问题是我无法追踪键/值组合应该进入的位置,也不知道如何添加它。代码如下。

我在http://forums.asp.net/t/1926444.aspx/1?given+key+was+not+present+in+the+dictionary发布了类似的讨论,但没有人知道如何帮助我。

void EmailUser(User user)
{
    user.ChangePasswordID = Guid.NewGuid();
    user.Save();
    MailMessage email = new MailMessage();
    //problem line below
    email.From = new MailAddress(Settings.LostPasswordEmailFrom);
    email.To.Add(new MailAddress(uxEmail.Text));
    email.Subject = Settings.LostPasswordSubject;
    email.Body = EmailTemplateService.HtmlMessageBody(EmailTemplates.MembershipPasswordRecovery, new { Body = Settings.LostPasswordText, BeginRequired = "", EndRequired = "", UserName = user.Name, GUID = user.ChangePasswordID.ToString() });
    email.IsBodyHtml = true;
    SmtpClient client = new SmtpClient();
    client.Send(email);

    uxSuccessPH.Visible = true;
    uxQuestionPanel.Visible = false;
    uxUserInfoPanel.Visible = false;
    uxUserNameLabelSuccess.Text = uxEmail.Text;
}

/// <summary>
/// The address that the lost password email will be sent from
/// </summary>
public static string LostPasswordEmailFrom
{
    get
    {
        if (String.IsNullOrEmpty(SiteSettings.GetSettingKeyValuePair()["LA_MembershipProvider_lostPasswordEmailFrom"]))
            return Globals.Settings.FromEmail;
        return SiteSettings.GetSettingKeyValuePair()["LA_MembershipProvider_lostPasswordEmailFrom"];
    }
}

1 个答案:

答案 0 :(得分:20)

当您拨打SiteSettings.GetSettingKeyValuePair()["LA_MembershipProvider_lostPasswordEmailFrom"])时,如果没有名为LA_MembershipProvider_lostPasswordEmailFrom的密钥,您将获得“字典中没有给定密钥”错误。你可以做的是,检查密钥是否先存在,然后获取值。你可以这样做

public static string LostPasswordEmailFrom
{
    get
    { 
        var kvp = SiteSettings.GetSettingKeyValuePair();

        if (kvp == null || !kvp.ContainsKey("LA_MembershipProvider_lostPasswordEmailFrom"))
            return Globals.Settings.FromEmail;
        return kvp["LA_MembershipProvider_lostPasswordEmailFrom"];
    }
}