我已经成功地从我的WebAPI项目("GET")接收了数据,但我的发布尝试不起作用。以下是相关的服务器/WebAPI 代码:
public Department Add(Department item)
{
if (item == null)
{
throw new ArgumentNullException("item");
}
departments.Add(item);
return item;
}
。这在"部门"上失败了。add(item);" 行,当从客户端调用此代码时:
const string uri = "http://localhost:48614/api/departments";
var dept = new Department();
dept.Id = 8;
dept.AccountId = "99";
dept.DeptName = "Something exceedingly funky";
var webRequest = (HttpWebRequest)WebRequest.Create(uri);
webRequest.Method = "POST";
var deptSerialized = JsonConvert.SerializeObject(dept); // <-- This is JSON.NET; it works (deptSerialized has the JSONized versiono of the Department object created above)
using (StreamWriter sw = new StreamWriter(webRequest.GetRequestStream()))
{
sw.Write(deptSerialized);
}
HttpWebResponse httpWebResponse = webRequest.GetResponse() as HttpWebResponse;
using (StreamReader sr = new StreamReader(httpWebResponse.GetResponseStream()))
{
if (httpWebResponse.StatusCode != HttpStatusCode.OK)
{
string message = String.Format("POST failed. Received HTTP {0}", httpWebResponse.StatusCode);
throw new ApplicationException(message);
}
MessageBox.Show(sr.ReadToEnd());
}
。在"HttpWebResponse httpWebResponse = webRequest.GetResponse() as HttpWebResponse;"行上失败。
服务器上的错误消息是部门为空; deptSerialized正在填充JSON"记录",因此...这里缺少什么?
更新
指定内容类型确实解决了这个难题。此外,状态代码是"已创建"的,使上面的代码抛出异常,所以我将其更改为:
using (StreamReader sr = new StreamReader(httpWebResponse.GetResponseStream()))
{
MessageBox.Show(String.Format("StatusCode == {0}", httpWebResponse.StatusCode));
MessageBox.Show(sr.ReadToEnd());
}
。它显示"状态代码 == 已创建",后跟 JSON"记录"(数组成员?我创造了。
您忘记设置正确的Content-Type
请求标头:
webRequest.ContentType = "application/json";
您在 POST 请求的正文中编写了一些 JSON 有效负载,但您如何期望 Web API 服务器知道您发送了 JSON 有效负载而不是 XML 或其他内容?您需要为此设置正确的内容类型请求标头。