我是Mailgun和REST的新手,需要一些帮助。
如果我使用Mailgun提供的代码:
RestClient client = new RestClient();
client.BaseUrl = "https://api.mailgun.net/v2";
client.Authenticator = new HttpBasicAuthenticator("api", "xxxx");
RestRequest request = new RestRequest();
request.Resource = "/address/validate";
request.AddParameter("address", "me@mydomain.com");
return client.Execute(request);
如何检索和处理地址有效的响应?
答案 0 :(得分:0)
首先您绝不应发布此类API的公钥等私人信息
只需使用惊人的Postman Chrome app,您就可以看到此类请求的结果:
click here以完整分辨率查看下方图片
我确定,如果您代替return client.Execute(request);
,那么
var result = client.Execute(request);
return result;
并在return
中添加断点,您可以检查从通话中传递的对象是什么...未经测试,我确定您可以转换result.Content
(因为它& #Rest; RestSharp将响应内容附加到对象中并使用该对象(或使用dynamic
类型)。
现在,在VS中测试你的代码:
click here以完整分辨率查看下方图片
然后您可以使用dynamic
对象,如:
click here以完整分辨率查看下方图片
public void GetResponse()
{
var client = new RestClient();
client.BaseUrl = "https://api.mailgun.net/v2";
client.Authenticator = new HttpBasicAuthenticator("api", "pubkey-e82c8201c292691ad889ace3434df6cb");
var request = new RestRequest();
request.Resource = "/address/validate";
request.AddParameter("address", "me@mydomain.com");
var response = client.Execute(request);
dynamic content = Json.Decode(response.Content);
bool isValid = content.is_valid;
string domain = content.parts.domain;
}
并像json传递的那样处理响应的内容:
{
"address": "me@mydomain.com",
"did_you_mean": null,
"is_valid": true,
"parts": {
"display_name": null,
"domain": "mydomain.com",
"local_part": "me"
}
}
答案 1 :(得分:0)
此代码适用于我。我没有使用RESTClient并编写了我自己的代码(完全正常)
[System.Web.Services.WebMethod]
public static object GetEmailInfo(string UserName)
{
var http = (HttpWebRequest)WebRequest.Create("https://api.mailgun.net/v2/address/validate?address=" + UserName);
http.Credentials = new NetworkCredential("api","public key");
http.Timeout = 5000;
try
{
var response = http.GetResponse();
var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();
JSON.JsonObject js = new JSON.JsonObject(content);
return Convert.ToBoolean(js["is_valid"]);
}
catch (Exception ex)
{
}
}