Unable to do a HTTP POST to a REST service passing

2019-09-03 11:09发布

问题:

I am trying to invoke(HTTP POST request) a REST web service from C# code passing json input. Below is the code i am using.

            MyModel myModelObj = new MyModel();
            myModelObj.code = "0003";
            myModelObj.qty = "3";
            var serializer = new JavaScriptSerializer();
            var jsonInput = serializer.Serialize(myModelObj);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            Byte[] byteArray = encoding.GetBytes(jsonInput);
            request.Method = "POST";
            request.ContentLength = byteArray.Length;
            request.ContentType = @"application/json"; 
            using (Stream dataStream = request.GetRequestStream())
            {
                dataStream.Write(byteArray, 0, byteArray.Length);
            }
            try
            {
                using (var response = (HttpWebResponse)request.GetResponse())
                {
                    var responseValue = string.Empty;
                    if (response.StatusCode != HttpStatusCode.OK)
                    {
                        var message = String.Format("Request failed. Received HTTP {0}", response.StatusCode);
                        throw new ApplicationException(message);
                    }
                    using (var responseStream = response.GetResponseStream())
                    {
                        if (responseStream != null)
                        using (var reader = new StreamReader(responseStream))
                        {
                            responseValue = reader.ReadToEnd();
                        }
                    }
                }
            }
            catch (WebException ex)
            {
                // Log exception and throw as for GET example above
            }

When I run this code am getting '(400) bad request' error, but when i try to invoke the same service using a jquery ajax call it worked. below is the jquery code used for invoking.

        $.ajax({
            type: "POST",
            url:"XXXXXXXXXXXXXXXXXXXXXXX",
            dataType : "json",
            data: {code:"0003", qty: "3"}
        }).done(function(response, status, request) {
            console.log("add cart :: ");
            console.log(response);
            console.log(request);
            updateCartCount();
        }).fail(function(error) {
            console.log(error);
        });

The service used in both the cases is same and the json input paramaters are also same, but I am able to get response using jquery but not in c#. For some reasons I had to implement this in C# only. Is there anything I need to change in the C# code and first of all whether my approach is correct? Can someone please help me on this? Thanks in advance! I am using .NET framework 4.5 with MVC 5. The line at which the exception raised is "using (var response = (HttpWebResponse)request.GetResponse())"