/// <summary>
/// DnsPod DDNS工具类
/// </summary>
public class DDNSToolkit
{
private static string userName = ConfigurationManager.AppSettings["DNSUserName"];
private static string password = ConfigurationManager.AppSettings["DNSPassword"];
/// <summary>
/// 公共参数
/// </summary>
private object baseParam = new
{
login_email = userName,//用户帐号,必选
login_password = password,//用户密码,必选
format = "json",//返回的数据格式,可选,默认为xml,建议用json
lang = "cn",//返回的错误语言,可选,默认为en,建议用cn
error_on_empty = "no"//没有数据时是否返回错误,可选,默认为yes,建议用no
}; #region 域名相关 /// <summary>
/// Return the domain_Id,when the domains contains more then one entity,returns the first one!
/// </summary>
/// <returns></returns>
public int DomainGetId(string keyword)//获取域名ID
{
var domainId = -;
if (!string.IsNullOrWhiteSpace(keyword))
keyword = "keyword=" + keyword;
/*api说明 https://www.dnspod.cn/docs/domains.html#domain-list
公共参数
type 域名权限种类,可选参数,默认为’all’。包含以下类型:
all:所有域名
mine:我的域名
share:共享给我的域名
ismark:星标域名
pause:暂停域名
vip:VIP域名
recent:最近操作过的域名
share_out:我共享出去的域名
offset 记录开始的偏移,第一条记录为 0,依次类推,可选参数
length 共要获取的记录的数量,比如获取20条,则为20,可选参数
group_id 分组ID,获取指定分组的域名,可选参数
keyword,搜索的关键字,如果指定则只返回符合该关键字的域名,可选参数*/
var dataBaseObj = GetDNSApi("https://dnsapi.cn/Domain.List", keyword);
if (dataBaseObj != null)
{
if (dataBaseObj["status"]["code"] == "")
{
if (dataBaseObj["domains"].Length > )
{
domainId = Convert.ToInt32(dataBaseObj["domains"][]["id"]);
}
}
else
{
throw new ArgumentException(string.Format("DNSPod API:Domain.List调用异常,说明:{0}", dataBaseObj["status"]["message"]));
}
}
return domainId;
} #endregion #region 记录相关
/// <summary>
/// Get the recordId
/// </summary>
/// <param name="domainId">domainId</param>
/// <param name="subDomain">The name for subDomain</param>
/// <returns></returns>
public int RecordGetIdBySubdomain(int domainId, string subDomain)//获取记录ID
{
var recordId = -;
/*api说明 https://www.dnspod.cn/docs/records.html#record-list
公共参数
domain_id 域名ID,必选
offset 记录开始的偏移,第一条记录为 0,依次类推,可选
length 共要获取的记录的数量,比如获取20条,则为20,可选
sub_domain 子域名,如果指定则只返回此子域名的记录,可选
keyword,搜索的关键字,如果指定则只返回符合该关键字的记录,可选*/
var dataBaseObj = GetDNSApi("https://dnsapi.cn/Record.List", new { domain_id = domainId, sub_domain = subDomain });
if (dataBaseObj != null)
{
if (dataBaseObj["status"]["code"] == "")
{
if (dataBaseObj["records"].Length > )
{
domainId = Convert.ToInt32(dataBaseObj["records"][]["id"]);
}
}
else
{
throw new ArgumentException(string.Format("DNSPod API:Record.List调用异常,说明:{0}", dataBaseObj["status"]["message"]));
}
} return recordId;
} /// <summary>
/// Create subdomain record
/// </summary>
/// <param name="domainId">domainId</param>
/// <param name="value">value:IP、CNAME、MX</param>
/// <param name="subDomain">subdomain name,like "www",defalut is "@"</param>
/// <param name="recordId"></param>
/// <returns></returns>
public bool RecordCreate(int domainId, string value, string subDomain, out int recordId)//创建记录
{
recordId = -;
bool flag = false;
/*api说明 https://www.dnspod.cn/docs/records.html#record-create
公共参数
domain_id 域名ID, 必选
sub_domain 主机记录, 如 www, 默认@,可选
record_type 记录类型,通过API记录类型获得,大写英文,比如:A, 必选
record_line 记录线路,通过API记录线路获得,中文,比如:默认, 必选
value 记录值, 如 IP:200.200.200.200, CNAME: cname.dnspod.com., MX: mail.dnspod.com., 必选
mx {1-20} MX优先级, 当记录类型是 MX 时有效,范围1-20, MX记录必选
ttl {1-604800} TTL,范围1-604800,不同等级域名最小值不同, 可选*/
var dataBaseObj = GetDNSApi("https://dnsapi.cn/Record.Create", new
{
domain_id = domainId,
sub_domain = subDomain,
value = value,
record_type = "A",
record_line = "默认"
});
if (dataBaseObj != null)
{
if (dataBaseObj["status"]["code"] == "")
{
flag = true;
recordId = Convert.ToInt32(dataBaseObj["record"]["id"]);
}
else
{
throw new ArgumentException(string.Format("DNSPod API:Record.Create调用异常,说明:{0}", dataBaseObj["status"]["message"]));
}
}
return flag;
}
/// <summary>
/// 修改记录
/// </summary>
/// <param name="domainId"></param>
/// <param name="recordId"></param>
/// <param name="subdomain"></param>
/// <param name="value"></param>
/// <param name="message"></param>
/// <returns></returns>
public bool RecordUpdate(int domainId, int recordId, string subdomain, string value, out string message)//修改记录
{
message = string.Empty;
bool flag = false;
/*api说明 https://www.dnspod.cn/docs/records.html#record-modify
公共参数
domain_id 域名ID,必选
record_id 记录ID,必选
sub_domain 主机记录,默认@,如 www,可选
record_type 记录类型,通过API记录类型获得,大写英文,比如:A,必选
record_line 记录线路,通过API记录线路获得,中文,比如:默认,必选
value 记录值, 如 IP:200.200.200.200, CNAME: cname.dnspod.com., MX: mail.dnspod.com.,必选
mx {1-20} MX优先级, 当记录类型是 MX 时有效,范围1-20, mx记录必选
ttl {1-604800} TTL,范围1-604800,不同等级域名最小值不同,可选*/
var resObj = GetDNSApi("https://dnsapi.cn/Record.Modify", new
{
domain_id = domainId,
record_id = recordId,
value = value,
sub_domain = subdomain,
record_type = "A",
record_line = "默认"
});
if (resObj != null)
{
if (resObj["status"]["code"] == "")
{
/*更新成功,返回记录详情(记录中的各参数)
* "record": {
* "id":16894439,
* "name":"@",
* "value":"3.2.2.2",
* "status":"enable"
* }
*/
message = GetObjectPropertiesString(resObj["record"]);
flag = true;
}
else
{
message = resObj["status"]["message"];
throw new ArgumentException(string.Format("DNSPod API:Record.Modify调用异常,说明:{0}", resObj["status"]["message"]));
}
}
return flag;
}
/// <summary>
/// 设置记录备注
/// </summary>
/// <param name="domainId">域名ID</param>
/// <param name="recordId">记录ID</param>
/// <param name="remark">备注信息</param>
/// <returns></returns>
public bool RecordRemark(int domainId, int recordId, string remark = "")//设置记录备注
{
bool flag = false;
var resObj = GetDNSApi("https://dnsapi.cn/Record.Remark", new
{
domain_id = domainId,
record_id = recordId,
remark = remark
});
if (resObj != null && resObj["status"]["code"] == "")
flag = true;
return flag;
} #endregion #region 辅助方法 /// <summary>
/// Send the webrequest to the api,and get the data of JSON!
/// </summary>
/// <param name="apiAddress">The API address for DNSPod</param>
/// <param name="data">The object type parameter with key/value pairs,like{type:"POST"}</param>
/// <returns></returns>
private dynamic GetDNSApi(string apiAddress, object data)
{
return GetDNSApi(apiAddress, GetApiParamDataString(data));
}
/// <summary>
/// Send the webrequest to the api,and get the data of JSON!
/// </summary>
/// <param name="apiAddress">The API address for DNSPod</param>
/// <param name="data">The data that will send to the api,like "type=post",split with "&" for more parameters!</param>
/// <returns>The returned data object</returns>
private dynamic GetDNSApi(string apiAddress, string data)
{ //若有额外参数,则将公共参数添加至参数请求中
if (!string.IsNullOrWhiteSpace(data))
{
data = string.Format("{0}&{1}", GetApiParamDataString(baseParam), data);
}
else
{
data = GetApiParamDataString(baseParam);//若无额外参数,只提交公共参数
}
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(apiAddress);
request.Method = "POST";
request.Headers.Add("content", "text/html; charset=UTF-8");
request.ContentType = "application/x-www-form-urlencoded";
request.UserAgent = "ROS DDNS/V1";
byte[] postData = Encoding.UTF8.GetBytes(data);
request.ContentLength = postData.Length;
Stream smp = request.GetRequestStream();//得到请求流
smp.Write(postData, , postData.Length);//写入请求流
smp.Close();//关闭流 HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader stream = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);
string responseString = stream.ReadToEnd();//得到返回数据
stream.Close();
response.Close();
request = null;
dynamic obj = null;
if (!string.IsNullOrWhiteSpace(responseString))
{
obj = new JavaScriptSerializer().Deserialize(responseString, typeof(object) as dynamic);
}
return obj;
}
/// <summary>
///
/// </summary>
/// <param name="data"></param>
/// <returns>The returned data of JSON</returns>
private string GetApiParamDataString(object data)
{
var dataString = string.Empty;
if (data != null)
{
//利用反复取可读属性或实例,返回属性集合
var objProperties = (from x in data.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance) where x.CanRead select x).ToList();
//将属性名与值拼接,返回string类型的数组
var arrProValue = (from y in objProperties select string.Format("{0}={1}", y.Name, y.GetValue(data, new object[]))).ToList().ToArray();
//将数组以“&”连接
dataString = string.Join("&", arrProValue);
}
return dataString;
}
private string GetObjectPropertiesString(object obj)
{
var dataStr = new StringBuilder();
if (obj != null)
{
var d = obj as Dictionary<string, object>;
foreach (var item in d)
{
dataStr.AppendLine(string.Format("{0} - {1}", item.Key, item.Value));
}
}
return dataStr.ToString();
} #endregion
} #region 辅助类,用于返回dynamic类型对象 public class JsonParser
{
/// <summary>
/// 从json字符串到对象。
/// </summary>
/// <param name="jsonStr"></param>
/// <returns></returns>
public static dynamic FromJson(string jsonStr)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
jss.RegisterConverters(new JavaScriptConverter[] { new DynamicJsonConverter() }); dynamic glossaryEntry = jss.Deserialize(jsonStr, typeof(object)) as dynamic;
return glossaryEntry;
}
}
public class DynamicJsonConverter : JavaScriptConverter
{
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
if (dictionary == null)
throw new ArgumentNullException("dictionary"); if (type == typeof(object))
{
return new DynamicJsonObject(dictionary);
} return null;
} public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
throw new NotImplementedException();
} public override IEnumerable<Type> SupportedTypes
{
get { return new ReadOnlyCollection<Type>(new List<Type>(new Type[] { typeof(object) })); }
}
} public class DynamicJsonObject : DynamicObject
{
private IDictionary<string, object> Dictionary { get; set; } public DynamicJsonObject(IDictionary<string, object> dictionary)
{
this.Dictionary = dictionary;
} public override bool TryGetMember(GetMemberBinder binder, out object result)
{
result = this.Dictionary[binder.Name]; if (result is IDictionary<string, object>)
{
result = new DynamicJsonObject(result as IDictionary<string, object>);
}
else if (result is ArrayList)
{
result = new List<DynamicJsonObject>((result as ArrayList).ToArray().Select(x => new DynamicJsonObject(x as IDictionary<string, object>)));
}
//else if (result is ArrayList && (result as ArrayList) is IDictionary<string, object>)
//{
// result = new List<DynamicJsonObject>((result as ArrayList).ToArray().Select(x => new DynamicJsonObject(x as IDictionary<string, object>)));
//}
//else if (result is ArrayList)
//{
// result = new List<object>((result as ArrayList).ToArray());
//}
return this.Dictionary.ContainsKey(binder.Name);
}
}
#endregion
05-06 05:55