我正在尝试传入一个Json String作为HttpWebRequest的参数以及一个URL。该请求将使方法很好,但每次参数为null。我试图遵循这样的许多例子,但没有成功:How to send json data in POST request using C#
以下是将被序列化并传递的示例对象
Amount amount = new Amount
{
currencyCode = "EUR",
amount = 1234
}
string JsonParameters = amount.ToJson();
var result = Methods.ExecuteHttpPostRequestWithJson("http://localhost:51581/Home/Test", JsonParameters);
Json参数正确序列化为
{"currencyCode":"EUR","amount":1234}
这是我尝试创建的方法。我尝试了多种方法,但每次最终都为空。
以下是将被称为
的方法public static string ExecuteHttpPostRequestWithJson(string URL, string Json)
{
string result = "";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(URL);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{;
streamWriter.Write(Json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
return result;
}
这是正确命中的方法,但是对于currencyCode和amount都有null参数。
[HttpPost]
public JsonResult Test(string currencyCode, string amount)
{
return Json(new
{
Test = "It worked"
});
}
答案 0 :(得分:1)
除了Nouman Bhatti在评论中建议的内容之外 - 定义服务中的金额等级以及更新服务的POST方法签名以期望该对象 - 也使用{ {1}}属性
类
[FromBody]
新的POST方法签名
new Amount
{
currencyCode = "EUR",
amount = 1234
}