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?
StatusCode 500: Internal Server Errormeans your web api controller is throwing an exception, have you debugged your controller action? If so what is the exception, does it get called at all? If not inspect the response and post the error message.