为什么我的Web API服务器的HttpWebRequest POST方法失败了?

时间:2013-10-17 19:51:33

标签: post asp.net-web-api json.net streamreader httpwebresponse

我已成功接收来自我的WebAPI项目(“GET”)的数据,但我尝试发布的帖子无效。这是相关的服务器/ WebAPI代码:

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

...在“departments.Add(item);”上失败了line,当调用来自客户端的代码时:

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()上失败,因为HttpWebResponse;”线。

服务器上的错误信息是部门为空; 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“记录”(数组成员?term。?)。

1 个答案:

答案 0 :(得分:3)

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

webRequest.ContentType = "application/json";

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