无法对通过C#传递json的REST服务执行HTTP POST

时间:2014-11-17 04:27:41

标签: c# ajax json rest http-post

我试图从传递json输入的C#代码调用(HTTP POST请求)REST Web服务。以下是我正在使用的代码。

            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
            }

当我运行此代码时,我遇到了错误的请求'错误,但当我尝试使用jquery ajax调用调用相同的服务时,它工作。下面是用于调用的jquery代码。

        $.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);
        });

两种情况下使用的服务是相同的,json输入参数也是相同的,但我能够使用jquery获得响应,但不能在c#中获得响应。出于某些原因,我只能在C#中实现它。 我需要在C#代码中进行更改,首先是我的方法是否正确?有人可以帮我这个吗?提前致谢! 我正在使用带有MVC 5的.NET framework 4.5。 引发异常的行是" 使用(var response =(HttpWebResponse)request.GetResponse())"

0 个答案:

没有答案