C# 如何修复 400 Bad Request 错误?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10131423/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 12:34:14  来源:igfitidea点击:

How to fix 400 Bad Request error?

c#

提问by Trey Copeland

I'm getting a The remote server returned an error: (400) Bad Requesterror when trying to run my code. Any help would be appreciated. Thanks.

我收到远程服务器返回错误:(400)尝试运行我的代码时出现错误请求错误。任何帮助,将不胜感激。谢谢。

    // Open request and set post data
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("myurl.com/restservice/Login");
    request.Method = "POST";
    request.ContentType = "application/json; charset:utf-8";
    string postData = "{ \"username\": \"testname\" },{ \"password\": \"testpass\" }";

    // Write postData to request url
    using (Stream s = request.GetRequestStream())
    {
        using (StreamWriter sw = new StreamWriter(s))
            sw.Write(postData);
    }

    // Get response and read it
    using (Stream s = request.GetResponse().GetResponseStream()) // error happens here
    {
        using (StreamReader sr = new StreamReader(s))
        {
            var jsonData = sr.ReadToEnd();
        }
    }

JSON EDIT

JSON 编辑

Changed to:

变成:

{ \"username\": \"jeff\", \"password\": \"welcome\" }

But still not working.

但仍然无法正常工作。

EDIT

编辑

This is what I found that works:

这是我发现有效的方法:

       // Open request and set post data
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("myurl.com/restservice/Login");
    request.Method = "POST";
    request.ContentType = "application/json";
    string postData = "{ \"username\": \"testname\", \"password\": \"testpass\" }";

    // Set postData to byte type and set content length
    byte[] postBytes = System.Text.UTF8Encoding.UTF8.GetBytes(postData);
    request.ContentLength = postBytes.Length;

    // Write postBytes to request stream
    Stream s = request.GetRequestStream();
    s.Write(postBytes, 0, postBytes.Length);
    s.Close();

    // Get the reponse
    WebResponse response = request.GetResponse();

    // Status for debugging
    string ResponseStatus = (((HttpWebResponse)response).StatusDescription);

    // Get the content from server and read it from the stream
    s = response.GetResponseStream();
    StreamReader reader = new StreamReader(s);
    string responseFromServer = reader.ReadToEnd();

    // Clean up and close
    reader.Close();
    s.Close();
    response.Close();

采纳答案by jorgehmv

can you try string postData = "[{ \"username\": \"testname\" },{ \"password\": \"testpass\" }]";

你能试一下吗 string postData = "[{ \"username\": \"testname\" },{ \"password\": \"testpass\" }]";

That way you are sending an array of 2 objects

这样你就发送了一个包含 2 个对象的数组

Edit: Also maybe what you really want to send is just an object with 2 properties, then it would be string postData = "{ \"username\": \"testname\", \"password\": \"testpass\" }"

编辑:也许你真正想要发送的只是一个具有 2 个属性的对象,那么它就是string postData = "{ \"username\": \"testname\", \"password\": \"testpass\" }"

回答by rastating

It looks as though it may be coming from the JSON you are posting as it is invalid, see below what you are sending but in a valid form:

看起来它可能来自您发布的 JSON,因为它无效,请参阅下面您发送的内容,但格式有效:

{
    "username": "testname",
    "password": "testpass"
}

回答by L.B

postData is not a valid Json object

postData 不是有效的 Json 对象

{ "username": "testname" },{ "password": "testpass" }

Try to use a Json parser like Json.Net, JavaScriptSerializeror DataContractJsonSerializerinstead of forming it manually

尝试使用 Json 解析器,如Json.NetJavaScriptSerializerDataContractJsonSerializer而不是手动形成它