C# 远程服务器返回错误:(400)
我试图将json数据发布到API中,但不断收到错误 System.Net.WebException:远程服务器返回错误:(400) 错误的请求 方法如下C# 远程服务器返回错误:(400),c#,asp.net,C#,Asp.net,我试图将json数据发布到API中,但不断收到错误 System.Net.WebException:远程服务器返回错误:(400) 错误的请求 方法如下 public string TestSubmitRequest() { try { string result = string.Empty; //var httpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Crea
public string TestSubmitRequest()
{
try
{
string result = string.Empty;
//var httpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("https://mytest/v1/Request");
var httpWebRequest = System.Net.WebRequest.CreateHttp("https://mytest.com/v1/Request");
httpWebRequest.ContentType = "application/json; charset=utf-8";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = new JavaScriptSerializer().Serialize("{\"Name\":\"chamara\",\"Email\":\"a@e.com\",\"Phone\":\"5345345\"," +
"\"RequireTeleHealth\":false,\"PreferredTime\":0,\"PreferredContactType\":1,\"FindOtherPsychologists\":false,\"Postcode\"" +
":\"3153\",\"Location\":{\"Suburb\":\"Bayswater\",\"Postcode\":\"3153\"},\"Issues\":[{\"Description\":\"Depression\"}]," +
"\"FundedPrograms\":[],\"ShortListedPsychologists\":[{\"Id\":\"047846\"},{\"Id\":\"156683\"},{\"Id\":\"158291\"},{\"Id\":\"019526\"},{\"Id\":\"031396\"}]}");
streamWriter.Write(json);
streamWriter.Flush();
}
var httpResponse = (System.Net.HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
return result;
}catch(Exception ex)
{
throw ex;
}
}
但是,相同的请求可以工作,并在Postman上返回预期结果
C代码怎么了?使用这个,它会工作的。它已经是一个json,因此无需进一步序列化它
string json = "{\"Name\":\"chamara\",\"Email\":\"a@e.com\",\"Phone\":\"5345345\"," +
"\"RequireTeleHealth\":false,\"PreferredTime\":0,\"PreferredContactType\":1,\"FindOtherPsychologists\":false,\"Postcode\"" +
":\"3153\",\"Location\":{\"Suburb\":\"Bayswater\",\"Postcode\":\"3153\"},\"Issues\":[{\"Description\":\"Depression\"}]," +
"\"FundedPrograms\":[],\"ShortListedPsychologists\":[{\"Id\":\"047846\"},{\"Id\":\"156683\"},{\"Id\":\"158291\"},{\"Id\":\"019526\"},{\"Id\":\"031396\"}]}";
用这个,它会工作的。它已经是一个json,因此无需进一步序列化它
string json = "{\"Name\":\"chamara\",\"Email\":\"a@e.com\",\"Phone\":\"5345345\"," +
"\"RequireTeleHealth\":false,\"PreferredTime\":0,\"PreferredContactType\":1,\"FindOtherPsychologists\":false,\"Postcode\"" +
":\"3153\",\"Location\":{\"Suburb\":\"Bayswater\",\"Postcode\":\"3153\"},\"Issues\":[{\"Description\":\"Depression\"}]," +
"\"FundedPrograms\":[],\"ShortListedPsychologists\":[{\"Id\":\"047846\"},{\"Id\":\"156683\"},{\"Id\":\"158291\"},{\"Id\":\"019526\"},{\"Id\":\"031396\"}]}";
“mytest”和“mytest.com”是一个问题吗?另外,除非有充分的理由保留它,否则这是相当古老的C#代码。现在你最好使用
HttpClient
,数据的DTO,以及像NewtonSoft这样的JSON序列化器来创建有效负载。“mytest”和“mytest.com”是一个问题吗?另外,除非有充分的理由保留它,否则这是相当古老的C代码。现在最好使用HttpClient
、数据的DTO和像NewtonSoft这样的JSON序列化程序来创建有效负载。