[英]C# HttpWebResponse sendin null JSON string
This has me really stumped. 这真让我感到难过。 I have a Web API handler for POST that looks like this:
我有一个用于POST的Web API处理程序,如下所示:
[HttpPost]
public IActionResult Post([FromBody]string jsonString)
{
if (jsonString == null)
return new ObjectResult("Bad JSON");
My caller looks like this (borrowed from How to post JSON to the server? ): 我的呼叫者看起来像这样(从“ 如何将JSON发布到服务器?”借来的):
public async void PostJson(string path, string payload)
{
string url = string.Format("{0}{1}", BaseAddress, path); // Not the issue, the URL is good...
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(payload);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
Console.WriteLine(string.Format("Response: {0}", result.ToString()));
Console.WriteLine("Press any key...");
Console.ReadKey();
}
} Here's the problem. 这就是问题所在。 When I use POSTMAN to post the JSON string (as supplied in payload), my WebApi gets the correct JSON string.
当我使用POSTMAN发布JSON字符串(在有效负载中提供)时,我的WebApi将获得正确的JSON字符串。 Yet, when I use the code listed above (and many other methods I've tried by researching this) I consistently get a NULL value for jsonString in my web api.
但是,当我使用上面列出的代码(以及研究过的其他许多方法)时,我在Web api中始终获得jsonString的NULL值。
Can anyone shed any light on this? 谁能对此有所启示?
I found the answer here: ASP.NET Core API POST parameter is always null 我在这里找到了答案: ASP.NET Core API POST参数始终为null
I must admit that I hadn't considered this approach when I first ran across it earlier in the day, but to paraphrase Sherlock Holmes, once you have exhausted the other possibilities... 我必须承认,当我在当天早些时候第一次遇到它时,我并没有考虑过这种方法,但是如果您已经穷尽了其他可能性,可以用夏洛克·福尔摩斯来解释一下……
In short, I changed the Content type to text/plain and added a formatter to my web api Startup.cs file (as shown in the other link) and this worked. 简而言之,我将“内容”类型更改为text / plain,并向我的Web api Startup.cs文件中添加了格式化程序(如其他链接中所示),并且可以正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.