向MailChimp添加新订户将返回错误请求

时间:2017-01-06 15:23:16

标签: c# restsharp mailchimp-api-v3.0

为了使用API​​ 3.0将订阅者添加到MailChimp列表,需要参数e-mailadress和status。如果请求成功,则响应将包含json格式的id。

我的问题是,当我使用我的成员类添加订阅者时,请求发送id,这是null,因此我得到错误Bad Request。如何将我的Member类更改为仅从响应中读取id而不将其添加到请求中?我正在使用RestSharp,Visual Studio 2013,.Net 4.0,

我的会员班看起来像这样

public class Member
{            
    public Member(){}
    public Member(string status)
    {
        this.status = status;
    }
    public Member(string email_address, string status)
    {
        this.status = status;
        this.email_address = email_address;
    }
    public string id { get; set; } 
    public string email_address { get; set; }
    public string status { get; set; }
}

我的createMember函数如下所示:

static void createMember()
{
    var client = new RestClient();
    client.BaseUrl = new Uri("https://" + dc + ".api.mailchimp.com/3.0");

    //HTML Basic Authentification
    client.Authenticator = new HttpBasicAuthenticator(usernsme, apiKey);

    var request = new RestRequest(Method.POST);
    request.Resource = "lists/{list_id}/members";

    request.AddUrlSegment("list_id", listId);

    request.RequestFormat = DataFormat.Json;

    request.AddBody(new Member(memberEmail, "subscribed"));

    RestClient.AddHandler();
    IRestResponse<Member> response2 = client.Execute<Member>(request);
    string _id = response2.Data.id;

    Console.WriteLine(response.StatusCode);
    Console.WriteLine(_id);
}

如果我从成员类中删除了ID,我可以将订阅者添加到列表中但是如何从响应中获取ID并使用它?

1 个答案:

答案 0 :(得分:2)

根据their reference,您调用的API方法与请求主体参数和响应主体参数不同,因此我建议使用两个不同的类。第一个是MemberRequest,用于请求,但没有id字段

public class MemberRequest
{
    public MemberRequest(){}

    public MemberRequest(string status)
    {
        this.status = status;
    }

    public MemberRequest(string email_address, string status)
    {
        this.status = status;
        this.email_address = email_address;
    }

    public string email_address { get; set; }
    public string status { get; set; }
}

,第二个是MemberResponse,用于响应并具有id字段

public class MemberResponse
{
    public string id { get; set; }
    public string email_address { get; set; }
    public string status { get; set; }
}

以下是createMember方法的样子

static void createMember()
{
    var client = new RestClient();
    client.BaseUrl = new Uri("https://" + dc + ".api.mailchimp.com/3.0");

    //HTML Basic Authentification
    client.Authenticator = new HttpBasicAuthenticator(usernsme, apiKey);

    var request = new RestRequest(Method.POST);
    request.Resource = "lists/{list_id}/members";

    request.AddUrlSegment("list_id", listId);

    request.RequestFormat = DataFormat.Json;

    request.AddBody(new MemberRequest(memberEmail, "subscribed"));

    IRestResponse<MemberResponse> response = client.Execute<MemberResponse>(request);
    string _id = response.Data.id;

    Console.WriteLine(response.StatusCode);
    Console.WriteLine(_id);
}