我正在尝试通过Last.fm实施授权。我将参数作为字典提交,以使签名更加容易。这是我用来签名呼叫的代码:
public static string SignCall(Dictionary<string, string> args)
{
IOrderedEnumerable<KeyValuePair<string, string>> sortedArgs = args.OrderBy(arg => arg.Key);
string signature =
sortedArgs.Select(pair => pair.Key + pair.Value).
Aggregate((first, second) => first + second);
return MD5(signature + SecretKey);
}
Run Code Online (Sandbox Code Playgroud)
我已经在调试器中检查了输出,这正是应该的输出,但是,每次尝试时我仍然会收到WebExceptions,这意味着API返回了“无效的方法签名”。这意味着它不接受SignCall正在生成的签名。
这是我用来生成URL的代码,以防万一:
public static string GetSignedURI(Dictionary<string, string> args, bool get)
{
var stringBuilder = new StringBuilder();
if (get)
stringBuilder.Append("http://ws.audioscrobbler.com/2.0/?");
foreach (var kvp in args)
stringBuilder.AppendFormat("{0}={1}&", kvp.Key, kvp.Value);
stringBuilder.Append("api_sig="+SignCall(args));
return stringBuilder.ToString();
}
Run Code Online (Sandbox Code Playgroud)
并获取用法示例以获取SessionKey:
var args = new Dictionary<string, string>
{
{"method", "auth.getSession"},
{"api_key", ApiKey},
{"token", token}
};
string url = GetSignedURI(args, true);
Run Code Online (Sandbox Code Playgroud)
编辑:
哦,代码引用了这样实现的MD5函数:
public static string MD5(string toHash)
{
byte[] textBytes = Encoding.UTF8.GetBytes(toHash);
var cryptHandler = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] hash = cryptHandler.ComputeHash(textBytes);
return hash.Aggregate("", (current, a) => current + a.ToString("x2"));
}
Run Code Online (Sandbox Code Playgroud)
另外,这是API文档:API-Last.fm,此页面详细介绍了授权。
你的代码对我来说工作得很好。我做了什么:
53c8890afbbf94281931cd11bf28a4e0WebClient返回用户名和会话密钥下载其内容。| 归档时间: |
|
| 查看次数: |
861 次 |
| 最近记录: |