如何使用httpwebrequest消费mvc 4 webapi服务

时间:2015-10-20 07:01:49

标签: asp.net-mvc asp.net-web-api httpwebrequest

我正在使用mvc 4 webapi服务。

string postData = string.Format("user={0}&pwd={1}", "me", "123");
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://sb2212.myaddresss.in/api/values/pavan?id=1&srt=2");
            webRequest.Method = "post";
            webRequest.ContentType = "application/json; charset=utf-8";
            webRequest.ContentLength = postData.Length;
            try
            {
                using ( StreamWriter requestWriter2 = new StreamWriter(webRequest.GetRequestStream()))
                {
                    requestWriter2.Write(postData);
                }

                using (StreamReader responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream()))
                {
                    // dumps the HTML from the response into a string variable
                    postData = responseReader.ReadToEnd();
                }

响应是"好的"但我得到了空洞的回应。 输出是" "

1 个答案:

答案 0 :(得分:0)

你可以使用HttpClientPostAsJson,post对象需要是Json对象而不是表单编码。

    var postData = JsonConvert.DeserializeObject(string.Format("{user={0},pwd={1}}", "me", "123"));


    using (var client = new HttpClient())
                {
                    string URL= "http://sb2212.myaddresss.in/api/values/pavan?id=1&srt=2";
                    var response = await client.PostAsJsonAsync(URL, postData );
                    var result= await response.Content.ReadAsStringAsync();
                    var resultobj = JsonConvert.DeserializeObject(result)

                }