对MailChimp API v3的发布请求始终返回未授权

时间:2016-03-05 02:48:07

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

我有以下调用来发布订阅Mailchimp列表但它未经授权返回。我有web密码,列表和用户名存储在web.config中,我已经三次检查。

using (var wc = new System.Net.WebClient())
{
    string parameters = string.Concat("email_address=", email, "&status=", "subscribed"),
           url = "https://us12.api.mailchimp.com/3.0/lists/" + ConfigurationManager.AppSettings["MailChimp.ListId"] + "/members";

    wc.Headers.Add("Content-Type", "application/json");

    wc.Credentials = new NetworkCredential("", ConfigurationManager.AppSettings["MailChimp.ApiKey"]);

    string result = wc.UploadString(url, parameters);
}

1 个答案:

答案 0 :(得分:3)

您的代码存在一些问题:

  1. 您将电子邮件地址和状态作为查询字符串参数而不是JSON
  2. 发送
  3. 以这种方式使用WebClient发送凭据无法正常工作。
  4. 尝试以下方法:

    var apiKey = "<api-key>";
    var listId = "<your-list-id>";
    var email = "<email-address-to-add>";
    
    using (var wc = new System.Net.WebClient())
    {
        // Data to be posted to add email address to list
        var data = new { email_address = email, status = "subscribed" };
    
        // Serialize to JSON using Json.Net
        var json = JsonConvert.SerializeObject(data);
    
        // Base URL to MailChimp API
        string apiUrl = "https://us12.api.mailchimp.com/3.0/";
    
        // Construct URL to API endpoint being used
        var url = string.Concat(apiUrl, "lists/", listId, "/members");
    
        // Set content type
        wc.Headers.Add("Content-Type", "application/json");
    
        // Generate authorization header
        string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(":" + apiKey));
    
        // Set authorization header
        wc.Headers[HttpRequestHeader.Authorization] = string.Format("Basic {0}", credentials);
    
        // Post and get JSON response
        string result = wc.UploadString(url, json);
    }