Asp.net mvc 如何使用httpwebrequest使用MVC4WebAPI服务
我正在使用MVC4WebAPI服务Asp.net mvc 如何使用httpwebrequest使用MVC4WebAPI服务,asp.net-mvc,asp.net-web-api,httpwebrequest,Asp.net Mvc,Asp.net Web Api,Httpwebrequest,我正在使用MVC4WebAPI服务 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.M
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();
}
回复是“OK”,但我得到的是空洞的回复。
输出为“”。您可以使用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)
}
HttpClient不适用于我。它表明使用System.Net.Http无法找到命名空间;如果您有使用Newtonsoft.Json的.NET4.0;使用nuget安装