DDNS动态更新
/// <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
DDNS动态更新的更多相关文章
- centos DNS服务搭建 DNS原理 使用bind搭建DNS服务器 配置DNS转发 配置主从 安装dig工具 DHCP dhclient 各种域名解析记录 mydns DNS动态更新 第三十节课
centos DNS服务搭建 DNS原理 使用bind搭建DNS服务器 配置DNS转发 配置主从 安装dig工具 DHCP dhclient 各种域名解析记录 mydns DNS动态更 ...
- RPi 2B DDNS 动态域名
/**************************************************************************** * RPi 2B DDNS 动态域名 * 说 ...
- Openshift 自建DDNS动态域名
某种情况下如openstack或者openshift/kubernetes软件部署过程由于需要标准的 域名系统(DNS UPDATE)RFC 2136中的动态更新功能, 但是现有的阿里云/华为云均不提 ...
- JSPatch – 动态更新iOS APP
原文:http://blog.cnbang.net/works/2767/ JSPatch是最近业余做的项目,只需在项目中引入极小的引擎,就可以使用JavaScript调用任何Objective-C的 ...
- JAVA代码热部署,在线不停服动态更新
本地debug的时候,可以实时编译并更新代码,线上也可以不停服来动态更新类,即所说的java热部署. JDK代理的两种方式: 1.premain方式是Java SE5开始就提供的代理方式,但其必须 ...
- elasticsearch同义词及动态更新
第一种:参考地址:http://dev.paperlesspost.com/setting-up-elasticsearch-synonyms/271.Add a synonyms file.2.Cr ...
- 在Android中实现service动态更新UI界面
之前曾介绍过Android的UI设计与后台线程交互,据Android API的介绍,service一般是在后台运行的,没有界面的.那么如何实现service动态更新UI界面呢?案例:通过service ...
- Android中动态更新ListView(转)
在使用ListView时,会遇到当ListView列表滑动到最底端时,添加新的列表项的问题,本文通过代码演示如何动态的添加新的列表项到ListView中.实现步骤:调用ListView的setOnSc ...
- Js多国时间动态更新
Js多国时间动态更新 点击下载
随机推荐
- Devexress XPO xpPageSelector 使用
在官网找到的.在这里做个备注. private void simpleButton1_Click(object sender, EventArgs e) { ) return; xpPageSelec ...
- jQuery Lightbox图片放大预览
简介:jQuery Lightbox图片放大预览代码是一款可以在用户点击页面中的小图片时,将该图片的高清版本以Lightbox的方式放大显示在页面的中间,提高用户的体验度. 效果展示 http://h ...
- Redis初识
安装与使用 Redis-x64-3.2.100:服务端 + 客户端 redis-3.2.5:源代码 Redis Desktop Manager - v0.8.8:客户端(基于Qt5的跨平台Redis桌 ...
- intellij idea 15 修改基础配置加载路径
一.概述 intellij idea 15 默认配置的启动加载路径是"C:\Users\Administrator.IntelliJIdea15",这样会导致占用C盘的空间越来越多 ...
- centos下升级mysql后遇到的小问题
记录今天遇到的一个小问题, 写一个app访问接口涉及到通过存储过程反馈多个结果集,但是反回多个结果集的存储过程,调用之后只能反回一个了,而且奇怪的是,即使直接在mysql上同时执行两条查询语句,第一条 ...
- 记录一次bug解决过程:resultType和手动开启事务
一.总结 二.BUG描述:MyBatis中resultType使用 MyBatis中的resultType类似于入参:parameterType.先看IDCM项目中的实际使用案例代码,如下: // L ...
- 来玩Play框架02 响应
作者:Vamei 出处:http://www.cnblogs.com/vamei 欢迎转载,也请保留这段声明.谢谢! 我上一章总结了Play框架的基本使用.这一章里,我将修改和增加响应. HTTP协议 ...
- 再谈HashMap
HashMap是一个高效通用的数据结构,它在每一个Java程序中都随处可见.先来介绍些基础知识.你可能也知 道,HashMap使用key的hashCode()和equals()方法来将值划分到不同的桶 ...
- maven常用插件集
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://mave ...
- Atitit.uke 团队建设的组织与运营之道attilax总结
Atitit.uke 团队建设的组织与运营之道attilax总结 1. intro引言:2 2. aims组织成立宗旨2 1.1. Mission组织使命2 1.2. val核心价值观2 1.3. c ...