Why is my HttpWebRequest POST method to my WebAPI

2019-05-17 06:33发布

问题:

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.