在MVC上添加Mailchimp联系人

时间:2017-08-07 21:25:27

标签: c# asp.net-mvc mailchimp mailchimp-api-v3.0

我希望在数据库中的表单注册时通过Mailchimp api在MVC控制器中添加Mailchimp订阅者。 所以我使用下面的代码与api key trully写道。

 public void AddContact(string email, string name, string surname, string listKey = "7f0c43ed8f")
        {
            string apiKey = "apikey comes here";
            string url = string.Format("https://us8.api.mailchimp.com/3.0/lists/{0}/members/", listKey);
            string data = "{\"email_address\": \"" + email + "\",\"status\": \"subscribed\",\"merge_fields\": {\"FNAME\": \"" + name + "\",\"LNAME\": \"" + surname + "\"}}";

            WebRequest myReq = WebRequest.Create(url);
            myReq.Method = "POST";
            myReq.ContentLength = data.Length;
            myReq.ContentType = "application/json; charset=UTF-8";

            string usernamePassword = "anystr:" + apiKey;
            UTF8Encoding enc = new UTF8Encoding();
            myReq.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(enc.GetBytes(usernamePassword)));


            using (Stream ds = myReq.GetRequestStream())
            {
                ds.Write(enc.GetBytes(data), 0, data.Length);
            }

            WebResponse wr = myReq.GetResponse();
            Stream receiveStream = wr.GetResponseStream();
            StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
            string content = reader.ReadToEnd();
        }

但是这段代码有时会起作用。有时它会出现“400 Bad Request”错误,我找不到有关此问题的任何错误或解决方案。 我感谢您的帮助。 提前谢谢。

0 个答案:

没有答案