我想通过mvc wepApi从桌面应用程序向服务器发送JSON。 这是我的桌面应用程序代码,它将数据转换为JSON并发送。通过JSON发送数据
private void btnAddUserType_Click(object sender, EventArgs e)
{
UserType userType = new UserType();
userType.UserTypeName = txtUserTypeName.Text;
string json = JsonConvert.SerializeObject(userType);
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:3852/api/default1");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream());
streamWriter.Write(json);
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
var streamReader = new StreamReader(httpResponse.GetResponseStream());
var responseText = streamReader.ReadToEnd();
}
,这是我的网页API
// POST api/default1
public void Post([FromBody]string value)
{
UserTypeRepository bl = new UserTypeRepository();
DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(UserType));
MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(value));
UserType u = new UserType();
u = (UserType)js.ReadObject(stream);
bl.Add(u);
}
但当交API的调用Value is null
。 为什么?
嗯......你可以尝试使用内容类型“application/json”吗?另外,在这种情况下,你可以尝试'public void Post([FromBody] UserType value)' - 你不必自己反序列化JSON。 此外,请通过调试并检查Request.Form对象(并查看在什么键下有什么可用)来检查您收到的内容。 – Gerino 2015-02-11 15:37:45
@Gerino,它没有工作! – nimaSadeghpour 2015-02-11 15:55:20
对我来说是一个简单的问题。 – 2015-02-11 17:39:52