我正在将一些python脚本转换为C#,并且无法使Web请求正常工作。 python代码是:
import json
import requests
import os
REST_URL = 'http://machinename:1234/webservicename'
payload = {'clientMessage': {
"UserName": "fred",
"MessageText": "message"
}
}
headers = {'content-type': 'application/json'}
res = requests.post(REST_URL, json.dumps(payload), headers=headers)
有人可以将其转换为C#吗?这是我遇到的“有效载荷”变量-C#等效项是什么?预先感谢
编辑-这是我到目前为止拥有的C#代码:
HttpClient client = new HttpClient();
var serializer = new JavaScriptSerializer();
string payload = "{ 'clientMessage': { \"UserName\": fred, \"MessageText\": message } }";
string jsonDumps = serializer.Serialize(payload);
var content = new StringContent(jsonDumps, Encoding.UTF8, @"application/json");
var postResult = client.PostAsync(_restUrl, content).Result;
答案 0 :(得分:0)
在C#中执行此操作的一种方法是创建一个anonymous object,然后对其进行序列化:
var payload = new
{
clientmessage = new
{
UserName = "fred",
MessageText = "message"
}
};
var json = JsonConvert.SerializeObject(payload);
结果:
{
"clientmessage": {
"UserName": "fred",
"MessageText": "message"
}
}