当我尝试向Web API中存在的方法提交POST请求时出现错误,发送的参数始终为NULL,下面我将提交WEB API POST方法:
public string Post([FromBody]string value)
{
var jsonObject = JsonConvert.DeserializeObject(value);
return jsonObject.ToString();
}
我确定上面的方法可以正常工作,正如我在POSTMAN上测试的那样,下面我将发布调用REST WEB API的方法:
static void Main(string[] args)
{
string fullURL = "http:/localhost:54029/api/values";
//Creating a Webrequest with any URL.
var httpWebRequest = (HttpWebRequest)WebRequest.Create(fullURL);
httpWebRequest.ContentType = "application/json";
//Defining Method type that will be used with this webrequest
httpWebRequest.Method = "POST";
//Creating the JSON Object with the required properties.
var json = new JObject(
new JProperty("Id", "ee288h0emlya"),
new JProperty("isDone", "False"),
new JProperty("stage", "Preparation"),
new JProperty("status", "Done"));
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
//Writing to the web service, emptying and closing the stream.
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
//Get the response from the server.
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
//Saving the response to result variable.
var result = streamReader.ReadToEnd();
Console.WriteLine(result);
}
当我使用第二种方法调用第一种方法时,参数值始终为 null ,因此我得到一个空的响应和错误。
有人可以帮忙吗?
答案 0 :(得分:0)
如果您接受参数作为字符串,那么您也应该将其作为字符串发送:
string json = "\"{ \\\"documentId\\\": \\\"Hmmm\\\", \\\"isDone\\\": \\\"YES\\\", \\\"stage\\\": \\\"Preparations\\\", \\\"status\\\": \\\"Done \\\"}\"";
另一种选择是创建一个DTO / Model类,然后像在代码中一样进行传递。