如何从C#向ASP.Net web api发出POST请求。 我使用了Newtonsoft DLL文件来创建json,但是,我无法将其发送到api。
我的代码是:
Login login = new Login
{
userid = username.Text,
pass = pass.Text
};
string json = JsonConvert.SerializeObject(login, Formatting.Indented);
如何将此json发送到web api并获得响应?
修改
string url = "myurl";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/json; charset=utf-8";
httpWebRequest.Method = "POST";
httpWebRequest.Accept = "application/json; charset=utf-8";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
json = json.Replace("\r\n","");
//json = json.Replace("\",", "\"," + "\"" +"\u002B");
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
pass.Text = result.ToString();
}
答案 0 :(得分:14)
我通过一些编辑使它成功。我没有直接序列化json对象,而是使用了一个类,并为其赋值,并使用JavaScriptSerializer对其进行序列化。谢谢你的帮助Shekhar。
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/json; charset=utf-8";
httpWebRequest.Method = "POST";
httpWebRequest.Accept = "application/json; charset=utf-8";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string loginjson = new JavaScriptSerializer().Serialize(new
{
userid = username.Text,
password = pass.Text
});
streamWriter.Write(loginjson);
streamWriter.Flush();
streamWriter.Close();
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
pass.Text = result.ToString();
}
}
答案 1 :(得分:1)
您可以使用HttpWebRequest
类创建请求,并使用StreamWriter
编写带有请求的Json,最后从Web API获取HttpWebResponse
。
var httpWebRequest = (HttpWebRequest)WebRequest.Create("path/api");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(json);
streamWriter.Flush();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
答案 2 :(得分:1)
Reg:“如何将此JSON发送到Web API并获得响应?”
您问题的当前现有答案均使用.NET的WebRequest;这是一个超级令人沮丧的库。我想提供“将JSON发送到Web API”的最简单,最简洁的方法。
开放源代码进行救援。有三种出色的开放源代码,免费的NuGet库可供选择。谢天谢地!这些都得到了很好的支持,记录和易于使用。
它们之间没有太多,但是我会给ServiceStack.Text一点优势……
好-在ServiceStack.Text中,JSON中的Post Request是什么样的?
var response = "http://example.org/login"
.PostJsonToUrl(new Login { Userid="admin", Password="mypassword" });
那是一行代码。简洁易用!将代码行与过于复杂的WebRequest进行比较