【发布时间】:2021-06-06 14:42:20
【问题描述】:
我有一个用 Javascript 编写的代码,我想将它转换为 C#。代码所做的是获取一个 javascript 对象,然后使用对象中的键值对创建一个字符串。你会如何在 C# 中做类似的事情。
这里是javascript代码
const userSession = {
application_id: 1111,
auth_key: "abc123456,
nonce: a456654,
timestamp: 1254564,
user: {
login : "johnwick",
password: 123434543
}
}
signParams(userSession) {
if (typeof userSession != 'object') {
throw Error('not an object');
}
let signature = Object.keys(userSession)
.map(elem => {
if (typeof userSession[elem] === 'object') {
return Object.keys(userSession[elem])
.map(elem1 => {
return elem + '[' + elem1 + ']=' + userSession[elem][elem1];
})
.sort()
.join('&')
}
else {
return elem + '=' + userSession[elem]
}
})
.sort()
.join('&')
return this.hmacSha1(signature);
}
signParams(userSession)
字符串应该是这样的 "application_id=3610&auth_key=aDRceQyTXSYEdJU&nonce=a456654×tamp=${timestamp}&user[login]=johnwick&user[password]=123434543"
这是我使用 c# 对象在 c# 中初始化对象的方法,因为 c# 中没有类似于 Javascript 对象的对象
public class UserSession
{
public int ApplicationId { get; set; }
public string AuthKey { get; set; }
public double Nonce { get; set; }
public double Timestamp { get; set; }
public string Signature { get; set; }
public dynamic User { get; set; }
}
public async Task<Session> GenerateSessionParams(User user)
{
string filename = "config.json";
using FileStream openStream = File.OpenRead(filename);
Config config = await JsonSerializer.DeserializeAsync<Config>(openStream);
Session session = new Session();
session.ApplicationId = config.cred.appId;
session.AuthKey = config.cred.authKey;
session.Nonce = this.RandomNonce();
session.Timestamp = this.GetTimeStamp();
if (user.Login != default && user.Password != default)
{
session.User = new { Login = user.Login, Password = user.Password };
}
else if (user.Email != default && user.Password != default)
{
session.User = new { Email = user.Email, Password = user.Password };
}
return session;
}
【问题讨论】:
-
为什么不能使用 Newtonsoft 来处理 JSON?
-
我是 c# 生态系统的新手,所以对它了解不多。我猜你的意思是在 C# 中使用 Newtonsoft 将 javascript 对象转换为 JSON,而不是创建 C# 类?
标签: javascript c# .net object