我想通过post方法调用服务器,但它无法正常工作

时间:2014-11-14 08:49:41

标签: c# .net rest windows-phone-8

我正在开发Windows Phone 8应用程序。我必须执行登录过程,然后我发送一些数据。我通过谷歌浏览器的POSTMAN使用了服务的网址。到现在为止还挺好。我尝试使用fiddler,虽然登录凭据很好,但我从服务器得到答案"无效请求"因为我没有设置Content-type:" application / json"。这样做之后一切顺利。在我的C#代码上,我再次得到了来自服务器的未经检查的答案,尽管mu凭证有效。我相信我没有正确设置Content-Type。贝娄是我的代码:

 public void UserAuthMethod(UserAuthMethod userAuth)
        {
            var request = (HttpWebRequest)WebRequest.Create("http://startaxi.punct.ro/api/init/userAuth");
            request.ContentType = "application/json";
            request.Headers[0] = "application/json"; //I tried to add this line but no results
            var postData = JsonConvert.SerializeObject(userAuth);
            var data = Encoding.Unicode.GetBytes(postData);

            request.Method = "POST";
            request.ContentLength = data.Length;

            var responseString = request.BeginGetResponse(GetResponseCallback, request);
        }

 void GetResponseCallback(IAsyncResult result)
        {
            HttpWebRequest request = result.AsyncState as HttpWebRequest;
            if (request != null)
            {
                try
                {
                    WebResponse response = request.EndGetResponse(result);
                    var reader = new StreamReader(response.GetResponseStream());
                    string result2 = reader.ReadToEnd();

                }
                catch (WebException e)
                {
                    return;
                }
            }
        }

我的代码出了什么问题?任何帮助将不胜感激! 提前谢谢你:)

2 个答案:

答案 0 :(得分:1)

Voila答案:

public void UserAuthMethod(UserAuthMethod userAuth)
        {
            WebClient webclient = new WebClient();
            Uri uristring = null;
            uristring = new Uri("http://startaxi.punct.ro/api/init/userAuth",UriKind.Absolute);//Please replace your URL here
            webclient.Headers["Content-type"] = "application/json";
            //content
            Dictionary<string, string> toSerialize = new Dictionary<string, string>();
            toSerialize.Add("email", userAuth.Email);
            toSerialize.Add("password", userAuth.Password);
            string JsonStringParams = JsonConvert.SerializeObject(toSerialize);

            webclient.UploadStringCompleted += wc_UploadStringCompleted;
            webclient.UploadStringAsync(uristring, "POST", JsonStringParams);
        }

        private void wc_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            //try
            {

                if (e.Result != null)
                {
                    string responce = e.Result.ToString();
                    //To Do Your functionality
                }
            }
           // catch
            {
            }
        }

答案 1 :(得分:0)

正如其他两位提到的那样,您永远不会在请求中设置数据! HttpWebRequest的文档显示了如何执行此操作。 http://msdn.microsoft.com/en-us/library/debx8sh9(v=vs.110).aspx