【问题标题】:Why is my HttpWebRequest POST method to my WebAPI server failing?为什么我的 WebAPI 服务器的 HttpWebRequest POST 方法失败?
【发布时间】:2013-10-26 11:41:47
【问题描述】:

我已成功从我的 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;”上失败行。

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

更新

指定 ContentType 确实解决了这个难题。另外,StatusCode是“Created”,使得上面的代码抛出异常,所以我把它改成了:

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

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

【问题讨论】:

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


    【解决方案1】:

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

    webRequest.ContentType = "application/json";
    

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

    【讨论】:

    • 好的,谢谢;我认为 JSON 是默认值。顺便说一句,那啤酒看起来不错。
    • 需要设置 webRequest.ContentLength 吗?
    • @ClayShannon,不,没必要。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-12
    • 1970-01-01
    • 2015-09-03
    • 2018-10-27
    • 1970-01-01
    • 1970-01-01
    • 2019-01-25
    相关资源
    最近更新 更多