不涉及任何数字或空值解析的 C# FormatException

C# FormatException without any numeric or null value parsing involved

此行抛出 FormatException:

var dataString = string.Format("email_address:{0}, status:subscribed, merge_fields:{1}", "a", "b");

毫无疑问,问题很明显,但我没有看到。

函数如下:

   public static string AddSubscriber(string listId, Subscriber subscriber) {

            string url = string.Format("https://us10.api.mailchimp.com/3.0/lists/{0}/members/", listId);

            var req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/json";
            req.Headers.Add("AUTHORIZATION", basicAuth);

            var mergeFieldJson = subscriber.MergeFields();
            var dataString = string.Format("email_address:{0}, status:subscribed, merge_fields:{1}", "a", "b"); // subscriber.email, mergeFieldJson);

            /*
            byte[] data = System.Text.Encoding.UTF8.GetBytes(dataString);
            using (var stream = req.GetRequestStream()) {
                stream.Write(data, 0, data.Length);
            }

            HttpWebResponse response = (HttpWebResponse)req.GetResponse();

            return new StreamReader(response.GetResponseStream()).ReadToEnd();
            */
            return "";
        }

例外情况:

Input string was not in a correct format. 
    at System.Text.StringBuilder.AppendFormat(IFormatProvider provider, String format, Object[] args)
    at System.String.Format(IFormatProvider provider, String format, Object[] args)
    at MailChimpLib.MailChimp.AddSubscriber(String listId, Subscriber subscriber) in d:\Development\GTPRepository\team24x7\trunk\MailChimpLib\MailChimp.cs:line 40
    at team24x7.Controllers.StoreController.AddTestSubscriber() in d:\Development\GTPRepository\team24x7\trunk\team24x7\api_source\Controllers\StoreController.cs:line 167

第 40 行是带有 string.Format(..) 的行。

这是 MergeFields 函数:

   public string MergeFields() {
        return string.Format("{'Email':'{0}','First Name':'{1}','Last Name':'{2}','Mascot':'{3}','Store Link':'{4}','School':'{5}'}",
            email, firstname, lastname, mascot, storelink, school
        );
    }

对我来说,它在调试模式下工作,但在发布模式下调用它之后的行中会导致异常。

毫无疑问,这个问题与在格式字符串中包含初始和结束花括号的愚蠢和错误的尝试有关。 (愚蠢的诅咒。)

我 运行 你在 Ideone 中的代码,它工作正常。

https://ideone.com/cHQC3O

using System;

public class Test
{
    public static void Main()
    {
        var dataString = string.Format("email_address:{0}, status:subscribed, merge_fields:{1}", "a", "b");
        Console.WriteLine(dataString);
    }
}

看来我们遗漏了代码中未提及的内容。

你遇到了什么异常?异常信息是什么?

经过几句评论,我们找到了问题的根源:

return string.Format("{'Email':'{0}','First Name':'{1}','Last Name':'{2}','Mascot':'{3}','Store Link':'{4}','School':'{5}'}",
    email, firstname, lastname, mascot, storelink, school
);

这里你得到 FormatException 因为你的字符串中有花括号 { 符号,这在格式化字符串时具有特殊含义。解决方案是用双花括号 {{}} 将其转义,因此您的代码变为:

return string.Format("{{'Email':'{0}','First Name':'{1}','Last Name':'{2}','Mascot':'{3}','Store Link':'{4}','School':'{5}'}}",
    email, firstname, lastname, mascot, storelink, school
);