在C#中使用Moz API

时间:2016-06-04 13:09:50

标签: c# .net api hash

我正在尝试在winform应用程序中访问Moz API。我查看了PHP指南,并尝试将其转换为C#,但我遇到了问题。

PHP的例外:https://github.com/seomoz/SEOmozAPISamples/blob/master/php/signed_authentication_sample.php

我认为这是我的签名搞砸了。在文档中它说:

“签名:您的访问ID的HMAC-SHA1哈希,Expires参数和您的密钥。安全哈希必须是base64编码,然后在Mozscape接受签名有效之前进行URL编码。”

long epochTicks = new DateTime(1970, 1, 1).Ticks;
long unixTime = ((DateTime.UtcNow.Ticks - epochTicks) / TimeSpan.TicksPerSecond) + 500;
var id = "mozscape-xxxxxxxx";
var secretKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx";
var enc = Encoding.ASCII;
HMACSHA1 hmac = new HMACSHA1(enc.GetBytes(secretKey));
hmac.Initialize();

var access = "mozscape-fa667096b" + "\r\n" + unixTime;

byte[] buffer = enc.GetBytes(access);
string signature = BitConverter.ToString(hmac.ComputeHash(buffer));

string signatureStep2 = System.Text.Encoding.UTF8.EncodeBase64(signature);
string signatureStep3 = HttpUtility.UrlEncode(signatureStep2);

有什么想法吗?我得到的错误是我的身份验证失败。

2 个答案:

答案 0 :(得分:0)

通过查看https://github.com/PixelMEDIA/SEOMozLib来解决这个问题。

这是正确生成密钥的方法:

public string CreateHashSignature(string strMozAccessId, string strMozSecretKey, string strTimeStamp)
    {
        string token = strMozAccessId + Environment.NewLine.Replace("\r", "") + strTimeStamp;

        using (var hmac = new HMACSHA1(Encoding.UTF8.GetBytes(strMozSecretKey), true))
        {
            var hash = hmac.ComputeHash(Encoding.ASCII.GetBytes(token));
            var hashString = BitConverter.ToString(hash).Replace("-", "").ToLower();
            return HttpUtility.UrlEncode(Convert.ToBase64String(hash));
        }
    }

答案 1 :(得分:-1)

您可以使用我的库LINQTOMOZ https://github.com/PavelMatua/LinqToMoz

只需将您的访问密钥和安全密钥放入MOZService构造函数即可。我们走了!

MOZService service = new MOZService("your access key","your security key");
var urlMetrics = service.QueryURLMetrics();
var result = urlMetrics.Where((arg) => sites.Contains(arg.SearchingURL) && arg.SourceCols == URLMetricsCols.FREE)
    .Select(x => new { equityLinkNumber = x.MetricsResult.ueid, cononicalURL = x.MetricsResult.uu })
    .OrderByDescending(x => x.equityLinkNumber);