maingun回复OK但没有任何反应

时间:2017-04-21 12:57:20

标签: c# dotnet-httpclient mailgun

Postman x-www-from-urlencoded和基本身份验证,一切正常。现在试着弄脏我的手,我只得到状态代码200,没有任何关于mailgun,没有记录日志。

using (var client = new HttpClient())
{
  client.BaseAddress = new Uri("https://api.mailgun.net/v3");

  client.DefaultRequestHeaders.Authorization = 
     new AuthenticationHeaderValue("api", "key-withheld-till-a-verdict-has-passed");

  var msg = new List<KeyValuePair<string, string>>
  {
    new KeyValuePair<string, string>("from",
        $"Excited User <mailgun@sandboxSOMEGUIDHERE.mailgun.org>"),
    new KeyValuePair<string, string>("to","approved-to-receive@mailgun"),
    new KeyValuePair<string, string>("subject", "Test Please Do Not Reply"),
    new KeyValuePair<string, string>("text","Thanks for borrowing me your inbox")
  };

  var request = new HttpRequestMessage(HttpMethod.Post, 
     "sandboxSOMEGUIDHERE.mailgun.org/messages");

  request.Content = new FormUrlEncodedContent(msg);

  var response = await client.SendAsync(request);
  // I get 200 status code

  var result = await response.Content.ReadAsStringAsync(); 
  //I get result = "Mailgun Magnificent API"         
}

1 个答案:

答案 0 :(得分:1)

首先,事实证明我得到了BaseAddress not right。我不得不在BaseAddress的末尾放一个斜杠。

 client.BaseAddress = new Uri("https://api.mailgun.net/v3/");

没有斜线,我发帖到(注意v3缺少),

https://api.mailgun.net/sandboxSOMEGUIDHERE.mailgun.org/messages

排除后,又出现了另一个问题401 - ANAUTHORIZED。在SO answer我的帮助下,

var byteArray = new UTF8Encoding()
    .GetBytes("api:key-withheld-till-a-verdict-has-passed");
client.DefaultRequestHeaders.Authorization =
     new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

mailgunOk做出回应的原因仍然很神秘。为了进一步调查,我使用Postman发布到

https://api.mailgun.net/sandboxSOMEGUIDHERE.mailgun.org/messages

令我惊讶的是,Mailgun神秘地回复了Ok