json 远程服务器返回错误:(四百)

eoxn13cs  于 2023-01-14  发布在  其他
关注(0)|答案(1)|浏览(140)

我尝试将json数据发布到API,但一直收到错误
System.Net.WebException:远程服务器返回错误:(400)错误请求
方法如下

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#代码有什么问题?

eit6fx6z

eit6fx6z1#

使用这个,它将工作。它已经是一个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\"}]}";

相关问题