Why is my HttpWebRequest POST method to my WebAPI server failing?

百般思念 提交于 2019-12-10 10:22:48

问题


I've successfully received data from my WebAPI project ("GET"), but my attempt to Post is not working. Here is the relevant server/WebAPI code:

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

...which fails on the "departments.Add(item);" line, when this code from the client is invoked:

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());
}

...which fails on the "HttpWebResponse httpWebResponse = webRequest.GetResponse() as HttpWebResponse;" line.

The err msg on the server is that departments is null; deptSerialized is being populated with the JSON "record" so...what is missing here?

UPDATE

Specifying the ContentType did, indeed, solve the dilemma. Also, the StatusCode is "Created", making the code above throw an exception, so I changed it to:

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

...which shows "StatusCode == Created" followed by the JSON "record" (array member? term.?) I created.


回答1:


You forgot to set the proper Content-Type request header:

webRequest.ContentType = "application/json";

You wrote some JSON payload in the body of your POST request but how do you expect the Web API server to know that you sent JSON payload and not XML or something else? You need to set the proper Content-Type request header for that matter.



来源:https://stackoverflow.com/questions/19435941/why-is-my-httpwebrequest-post-method-to-my-webapi-server-failing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!