I'm having trouble sending a JSON object to my MVC 6 WebApi controller.
When I look at the RAW data in fiddler, what I'm currently sending, is this:
Username=brugernavn&Password=adgangskode&DocumentId=document.dotx
What I think my controller is expecting to recieve, is this:
{"Username":"brugernavn","Password":"adgangskode","DocumentId":"document.dotx"}
My controller code:
namespace DemoApp.Controllers
{
[Route("api/[controller]")]
public class DocumentController : Controller
{
// POST: api/documentcontroller/GetDocumentInformation
[HttpPost]
[Route("[action]")]
public string GetDocumentInformation([FromBody] GetDocumentInformationRequest documentInformationRequest)
if (documentInformationRequest == null)
{
return "null";
} else {
return "ok";
}
}
}
My GetDocumentInformationRequest model class:
public class GetDocumentInformationRequest
{
public string Username { get; set; }
public string Password { get; set; }
public string DocumentId { get; set; }
}
My jQuery code:
var source = {
'Username': 'brugernavn',
'Password': 'adgangskode',
'DocumentId': documentID
}
var apiUrl = location.origin + "/api/documentcontroller/GetDocumentInformation";
$.ajax({
type: "POST",
dataType: "json",
url: apiUrl,
data: source,
success: function (data) {
alert(data);
},
error: function (error) {
var x = error; //break here for debugging.
}
});
The ajax request does hit the controller, but the documentInformationRequest parameter is null.
Also the ajax request ends up in the error-block every time, but thats because the controller currently just returns "null" which is not valid JSON... (It does return a code 200, and no error is thrown.)
I have tried many variations of the ajax request, but so far none have resulted in sending the JSON object to the controller correctly.