使用C#调用REST服务时出现HTTP 500错误

时间:2014-05-30 16:31:48

标签: c# rest asp.net-web-api

通过c#调用以下REST时出现HTTP 500错误,但我可以使用chrome REST控制台进行POST

发送请求正文(来自REST控制台)

Request Url: http://dev-6666.amazonaws.com/CourseEnrollment
Request Method: POST
Status Code: 201
Params: {
    "MESSAGE-TYPE": "UserEnrollmentCreate",
    "PAYLOAD": "<userstd version=\"\"\"\"><user password=\"\"PSEUDO-5621b55a\"\" lastname=\"\"Wara\"\" emailaddress=\"\"student3@bloody.com\"\" loginid=\"\"BloodyStudent3\"\" firstname=\"\"Buddihi\"\" userid=\"\"19658121\"\" clientid=\"\"117112\"\" createdate=\"\"2014-04-29T03:55:54.873\"\" lastupdate=\"\"2014-05-29T03:55:54.873\"\"><userproperty propertyname=\"\"\"\" propertyvalue=\"\"\"\" createdate=\"\"\"\" lastupdate=\"\"\"\"></userproperty></user></userstd>"
}

使用的C#方法(这是一个得到500的错误)

 private void TestCreateUser()
        {

            string requestData = "{\"MESSAGE-TYPE\":UserEnrollmentCreate,\"PAYLOAD\":\"<userstd version=\"\"\"\"><user password=\"\"PSEUDO-5621b55a\"\" lastname=\"\"Wara\"\" emailaddress=\"\"student3@bloody.com\"\" loginid=\"\"BloodyStudent3\"\" firstname=\"\"Buddihi\"\" userid=\"\"19658121\"\" clientid=\"\"117112\"\" createdate=\"\"2014-04-29T03:55:54.873\"\" lastupdate=\"\"2014-05-29T03:55:54.873\"\"><userproperty propertyname=\"\"\"\" propertyvalue=\"\"\"\" createdate=\"\"\"\" lastupdate=\"\"\"\"></userproperty></user></userstd>}";

            byte[] data = Encoding.UTF8.GetBytes(requestData);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://dev-6666.amazonaws.com/CourseEnrollment");
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            Stream dataStream = request.GetRequestStream();
            dataStream.Write(data, 0, data.Length);
            dataStream.Close();

            WebResponse response = request.GetResponse();
            string result = new StreamReader(response.GetResponseStream()).ReadToEnd();

        }

2 个答案:

答案 0 :(得分:1)

form-url编码的数据应该是格式(variablename)=(data)&amp;(variablename)=(data)....

控制台表示有点乱,所以真正的数据字符串应该是

string requestData = "MESSAGE-TYPE=UserEnrollmentCreate&PAYLOAD=<userstd version=\"\"\"\"><user password=\"\"PSEUDO-5621b55a\"\" lastname=\"\"Wara\"\" emailaddress=\"\"student3@bloody.com\"\" loginid=\"\"BloodyStudent3\"\" firstname=\"\"Buddihi\"\" userid=\"\"19658121\"\" clientid=\"\"117112\"\" createdate=\"\"2014-04-29T03:55:54.873\"\" lastupdate=\"\"2014-05-29T03:55:54.873\"\"><userproperty propertyname=\"\"\"\" propertyvalue=\"\"\"\" createdate=\"\"\"\" lastupdate=\"\"\"\"></userproperty></user></userstd>";

答案 1 :(得分:1)

当您将application/x-www-form-urlencoded作为内容发布时指定application/json时,响应应该在工作实现中为400。

WebApi可能返回500,因为它试图将内容解码为表单,而内容实际上是JSON,因此它是一个例外,因此返回500作为状态代码。