Reputation: 124
I've been trying for days to find a proper way to post an object to a Web API controller method using a C# client (specifically, my Windows Forms application). Here is my code for calling the Web API with the object:
private async void insertDocument(Document doc)
{
using (var client = new HttpClient())
{
var response = await client.PostAsJsonAsync(
Constants.API_ROOT_URI + "Documents/Post", doc);
if (response.IsSuccessStatusCode)
{
MessageBox.Show("Document posted successfully.");
}
else
{
MessageBox.Show("Document NOT posted successfully.");
}
}
}
Here my controller POST method in my Web API:
// POST api/Documents (INSERT)
public HttpResponseMessage Post([FromBody] Document doc)
{
if (doc == null)
{
Request.CreateErrorResponse(HttpStatusCode.BadRequest,
"Could not read the Document from body");
}
bool success = docBL.insertDocumentEntry(doc);
if (success)
{
return Request.CreateResponse(HttpStatusCode.OK);
}
return Request.CreateErrorResponse(HttpStatusCode.BadRequest,
"Could not save Document model to database");
}
And finally here is my routing template in my WebApiConfig
file:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
I've tried many ways to do this and properly get my Document object from my C# UI client to my Web API controller method, and every way I have tried has resulted in a "StatusCode 500: Internal Server Error" from my response variable in my insertDocument
method when I debug with a breakpoint. Could someone please tell me what I'm doing wrong?
Upvotes: 1
Views: 2208
Reputation: 124
I found out what I was doing wrong, I'm surprised it took me this long to see the error!
It turns out that I was not filling out all attributes of the object I was passing as a JSON to my Web API. Some objects encapsulated in the head object were not given values so the API registered the JSON as an invalid Document object.
Thanks for all the comments!!!
Upvotes: 1