.NET调用腾讯云API实现域名动态解析

电信宽带申请了公网IP,但是IP不是固定的随时都可能会变化。腾讯云提供了域名解析的相关操作的API,我们可以获取本机IP和域名解析的IP去做比对,不一致就更新解析,直接来看核心代码,下面是调用代码,传入相关参数即可。下面核心代码已写好,关于获取本机ip和定时任务(定时修改解析)可以根据你的具体环境去实现

//添加一个域名解析
var dic = new Dictionary<string, string>
{
    {"Action", "RecordCreate"},
    {"domain", "liutianyou.com"},
    {"subDomain", "b.liutianyou.com"},
    {"recordType", "A"},
    {"value", "113.104.236.131"},
    {"recordLine", "默认"}
};

var content = new TencentDDNS_New().OperateRecord(dic);

_secretKey和_secretKey去腾讯云控制台查看,改为自己的

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using static System.TimeZone;

namespace BeeDDNS.Test
{
    public class TencentDDNS_New
    {
        /// <summary>
        ///     构造函数
        /// </summary>
        public TencentDDNS_New()
        {
            _client = new HttpClient(new HttpClientHandler { UseCookies = true });
            _client.DefaultRequestHeaders.Add("user-agent",
                "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.0");
            _client.DefaultRequestHeaders.Add("Connection", "Keep-Alive");
            _client.DefaultRequestHeaders.Add("Keep-Alive", "timeout=600");
            _client.DefaultRequestHeaders.Add("ContentType", "application/x-www-form-urlencoded");
            _client.BaseAddress = new Uri("https://" + _url);

            _time = GetTimestamp();
            _nonce = new Random().Next().ToString();
            _signatureMethod = "HmacSHA256";
        }

        /// <summary>
        ///     操作解析
        /// </summary>
        public async Task<string> OperateRecord(Dictionary<string, string> parameterDic)
        {
            //公共参数
            var dic = new Dictionary<string, string>
            {
                {"Nonce", _nonce},
                {"SecretId", _secretId},
                {"SignatureMethod", _signatureMethod},
                {"Timestamp", _time}
            };

            //合并接口参数
            dic = dic.Union(parameterDic).ToDictionary(k => k.Key, v => v.Value);

            //字典Ascii排序
            dic = AsciiDictionary(dic);

            //获取签名
            var data = "POST" + _url + _urlPath + "?";
            foreach (var item in dic)
                data += item.Key.ToLower() == "recordid"
                    ? "&" + item.Key + "=" + Convert.ToInt32(item.Value)
                    : "&" + item.Key + "=" + item.Value;
            _signature = HmacSha256(data.Replace("?&", "?"));

            //添加签名
            dic.Add("Signature", _signature);

            var respond = _client.PostAsync(_urlPath,
                new FormUrlEncodedContent(dic)).Result;

            //如果你使用GET就将上面的参数再过一遍UrlEncode,然后直接拼url
            return await respond.Content.ReadAsStringAsync();
        }

        #region
        /// <summary>
        ///     SecretId
        /// </summary>
        private const string _secretId = "**********";

        /// <summary>
        ///     SecretKey
        /// </summary>
        private const string _secretKey = "**********";

        private readonly HttpClient _client;

        private const string _url = "cns.api.qcloud.com";

        private const string _urlPath = "/v2/index.php";

        /// <summary>
        ///     UNIX 时间戳
        /// </summary>
        private readonly string _time;

        /// <summary>
        ///     随机正整数
        /// </summary>
        private readonly string _nonce;

        /// <summary>
        ///     请求签名
        /// </summary>
        private string _signature;

        /// <summary>
        ///     签名方式
        /// </summary>
        private readonly string _signatureMethod;
        #endregion

        #region 私有方法
        /// <summary>
        ///     获取UNIX格式的时间戳
        /// </summary>
        private string GetTimestamp()
        {
            var startTime = CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            return ((int)(DateTime.Now - startTime).TotalSeconds).ToString();
        }

        /// <summary>
        ///     字典Ascii排序
        /// </summary>
        /// <param name="dic"></param>
        /// <returns></returns>
        private Dictionary<string, string> AsciiDictionary(Dictionary<string, string> dic)
        {
            var asciiDic = new Dictionary<string, string>();
            var arrKeys = dic.Keys.ToArray();
            Array.Sort(arrKeys, string.CompareOrdinal);
            foreach (var key in arrKeys)
            {
                var value = dic[key];
                asciiDic.Add(key, value);
            }

            return asciiDic;
        }

        /// <summary>
        ///     url编码字符
        /// </summary>
        private string UrlEncode(string str)
        {
            var builder = new StringBuilder();
            foreach (var c in str)
                if (HttpUtility.UrlEncode(c.ToString()).Length > 1)
                    builder.Append(HttpUtility.UrlEncode(c.ToString()).ToUpper());
                else
                    builder.Append(c);
            return builder.ToString();
        }

        /// <summary>
        ///     HmacSha256加密
        /// </summary>
        /// <param name="data">加密文本</param>
        /// <param name="key">密钥</param>
        private static string HmacSha256(string data, string key = _secretKey)
        {
            using var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(key));
            return Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(data))).Replace("-", "");
        }

        #endregion
    }
}

暂无评论

相关推荐

微信扫一扫,分享到朋友圈

.NET调用腾讯云API实现域名动态解析