【问题标题】:Post request to MailChimp API v3 always returns unauthorized对 MailChimp API v3 的发布请求总是返回未经授权的
【发布时间】:2016-06-18 23:24:21
【问题描述】:

我有以下调用发布订阅 Mailchimp 列表,但它返回未经授权。我在 web.config 中存储了 API 密钥、列表和用户名,并对其进行了三次检查。

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);
}

【问题讨论】:

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


    【解决方案1】:

    您的代码有几个问题:

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

    尝试以下方法:

    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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-03
      • 2020-04-26
      • 1970-01-01
      • 2018-09-27
      • 1970-01-01
      • 2015-11-08
      • 2012-12-23
      • 1970-01-01
      相关资源
      最近更新 更多