Why is my HttpWebRequest POST method to my WebAPI server failing?
Asked Answered
L

1

3

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.

Lasky answered 17/10, 2013 at 19:51 Comment(0)
T
3

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.

Thessalonian answered 17/10, 2013 at 20:3 Comment(3)
Okay, thanks; I thought JSON was the default. BTW, that beer looks pretty good.Lasky
Is setting webRequest.ContentLength necessary?Lasky
@ClayShannon, no, it's not necessary.Thessalonian

© 2022 - 2024 — McMap. All rights reserved.