我有一个用nodejs编写并开发c#客户端的Web服务。我对GET方法没有任何问题,但对POST有问题。
这是我的客户代码
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = methodType.ToString();
UTF8Encoding encoding = new UTF8Encoding();
if (!string.IsNullOrEmpty(content))
{
Byte[] byteArray = encoding.GetBytes(content);
request.ContentLength = byteArray.Length;
using (var dataStream = request.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}
}
request.ContentType = "application/json";
try
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
return response;
}
}
.....
这是我的服务器代码
router.post('/api/activation/activate', urlencodedParser, (req, res, next) => {
return new Promise(function (resolve, reject) {
(async function () {
try {
routerAppFeature.Delete(req.body.type.toUpperCase(), req.body.id);
console.log(req.body.HardwareId);
console.log(req.params.HardwareId)
console.log(req.query.HardwareId);
var result = { "data": "Okay :)" + req.body.HardwareId, "errorCode": "-1" };
res.json(result);
} catch (error) {
console.log('!!Error in activate method: ' + error);
return reject(error);
}
})();
}).catch(error => {
var err = { "message": error.message, "errorCode": "1" };
res.json(err);
});
});
所以我的问题是
使用执行后,使用(var dataStream = request.GetRequestStream())
我的post方法被触发,req.body为空,因为在触发该方法之前我没有传递任何参数。
我该如何解决这个问题?
答案 0 :(得分:0)
我已经解决了问题。我仍然不知道真正的问题是什么,但是下面的代码可以正常工作。
public void Test(string content)
{
using (var client = new HttpClient())
{
try
{
var res = client.PostAsync("http://localhost:4000/api/activation/activate",
new StringContent(content, Encoding.UTF8, "application/json");
res.Result.EnsureSuccessStatusCode();
Console.WriteLine("Response " + res.Result.Content.ReadAsStringAsync().Result +
Environment.NewLine);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
因此它与nodejs无关,但与C#无关。