3

我已成功从我的 WebAPI 项目(“GET”)接收数据,但我的 Post 尝试不起作用。这是相关的服务器/WebAPI 代码:

public Department Add(Department item)
{
    if (item == null)
    {
        throw new ArgumentNullException("item");
    }
    departments.Add(item);
    return item; 
}

...在“departments.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;”上失败 线。

服务器上的 err msg 是部门为空;deptSerialized 正在填充 JSON“记录”所以......这里缺少什么?

更新

指定 ContentType 确实解决了这个难题。此外,StatusCode 是“已创建”,使上面的代码抛出异常,所以我将其更改为:

using (StreamReader sr = new StreamReader(httpWebResponse.GetResponseStream()))
{
    MessageBox.Show(String.Format("StatusCode == {0}", httpWebResponse.StatusCode));
    MessageBox.Show(sr.ReadToEnd());
}

...它显示“StatusCode == Created”,然后是我创建的 JSON“记录”(数组成员?术语。?)。

4

1 回答 1

3

您忘记设置正确的Content-Type请求标头:

webRequest.ContentType = "application/json";

您在 POST 请求的正文中编写了一些 JSON 有效负载,但是您希望 Web API 服务器如何知道您发送的是 JSON 有效负载而不是 XML 或其他内容?您需要为此设置正确的 Content-Type 请求标头。

于 2013-10-17T20:03:30.377 回答