gpt4 book ai didi

c# - StringContent 作为空对象发送到 Node

转载 作者:太空宇宙 更新时间:2023-11-03 21:50:25 26 4
gpt4 key购买 nike

我有一个 C# 桌面,需要使用 HttpClient 向我的 Node API 发出发布请求。问题是 Node 应用程序收到的 JSON 与我想要的不同。我尝试使用下面的示例,并从 StringContent 中读取,发现它包含我期望的值,但它在 Node 应用程序上显示为 {};

User user = new User
{
Username = username,
Password = password
};
StringContent content = new StringContent(JsonConvert.SerializeObject(user));
HttpResponseMessage response = await client.PostAsJsonAsync("auth", content);

我也尝试过类似的代码,但我只使用了这样的字符串,而不是 StringContent:


User user = new User
{
Username = username,
Password = password
};
StringContent content = JsonConvert.SerializeObject(user);
HttpResponseMessage response = await client.PostAsJsonAsync("auth", content);

但这给了我一个关于 JSON 中位置 0 处的 Unexpected Token "的错误;

请帮助我了解如何发送正确序列化的用户对象。如果可能的话,我更愿意在不实现 ISerialized 的情况下执行此操作。这是我的用户数据类:

namespace Cloud_Calendar
{
class User
{
public string Username { get; set; }
public string Password { get; set; }
}
}

我认为查看我的 Node 正在做什么可能很有用,所以这里是:

let failCount = 0;
app.all('/failAuth', (req, res) => {
console.log("failed" + (++failCount));
console.log(req.body);
res.send('failure to authenticate user');
});

app.post('/main', (req, res) => { //this will be removed & replaced with routes for each action
res.send('success');
});


app.post('/auth', passport.authenticate('local', { failureRedirect: '/failAuth' }), (req, res) => {
//TODO: if success parse req.body to search for req.body.action variable and redirect based on value
console.log(`req.body.action: ${req.body.action}`); //this indicates desired action
try{
res.redirect(308, '/main');
}catch(err){
console.error(err);
}
});

req.body 被记录为空...这是因为重定向吗?

最佳答案

使用PostAsJsonAsync,您需要按原样传递对象。在内部,它将序列化对象,创建一个 StringContent 并通过 HttpClient

发布它

因此,要么按照预期使用 PostAsJsonAsync

User user = new User
{
Username = username,
Password = password
};
HttpResponseMessage response = await client.PostAsJsonAsync("auth", user);

或者自己执行序列化(基本上是 PostAsJsonAsync 内部执行的操作)

User user = new User
{
Username = username,
Password = password
};
string json = JsonConvert.SerializeObject(user);
StringContent content = new StringContent(josn, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync("auth", content);

关于c# - StringContent 作为空对象发送到 Node ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60013246/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com