Reputation: 47
The problem is, when the method is entered, "session" is a null. As you can see, headers and JSON-object are correct. Could you tell me what I'm doing wrong?
My POST-request with angular:
$scope.send = function () {
var data = { "session": session };
var req = {
method: 'POST',
data: data,
headers: {'Content-Type': 'application/json'},
url: '/api/myquiz/answers/'
}
$http(req).success(
function () {
quiz();
});
}
and C# code:
[Route("answers")]
[HttpPost]
public IActionResult AnswerPost([FromBody] string session) {
...
}
Chrome console:
Request URL:http://localhost:39634/api/myquiz/answers/
Request Headers
Provisional headers are shown
Accept:application/json, text/plain, */*
Content-Type:application/json
Origin:http://localhost:39634
Referer:http://localhost:39634/Team/Index
User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36
Request Payload
{session: "92dfb7e432224702a553c98c294b29cf"}
session: "92dfb7e432224702a553c98c294b29cf"
Upvotes: 1
Views: 1926
Reputation: 39015
Web API actions require a value matching the parameter type to be able to deserialize the body.
So, if your Web API parameter is a value type, like your string session
, you have to post a single value, i.e. something like 'my string'
, without extra wrappers.
If your Web API parameter was a complex one, for example a class with properties, then you would have to post a JSON object, like you do in your question.
I.e. your parameter should be an object of a class like this:
public class ParamClass
{
public string session { get; set; } // Note: it's case.sensitive
}
Upvotes: 1
Reputation: 11474
You are posting an object to WebApi:
var data = { "session": session };
With this you are saying that you are passing an object that has a session property on it. What you are telling your WebApi method to expect though is a string:
public IActionResult AnswerPost([FromBody] string session)
not an object. I think if you change your code to this:
$scope.send = function () {
//var data = { "session": session };
var req = {
method: 'POST',
data: session,
headers: {'Content-Type': 'application/json'},
url: '/api/myquiz/answers/'
}
$http(req).success(
function () {
quiz();
});
}
It should work. Hope this helps. If you are going to pass more params to the function in the future though, I would create a C# object to pass to the controller. like this:
public class AnswerPost
{
public string Session {get; set;}
}
and then update the controller method to look like this:
[Route("answers")]
[HttpPost]
public IActionResult AnswerPost([FromBody] AnswerPost answerpost) {
...
}
Upvotes: 1
Reputation: 5270
Per Web API documentation, try directly sending session (raw json string) instead of putting it in a dictinary (json object).
var req = {
method: 'POST',
data: '"' + session + '"',
headers: {'Content-Type': 'application/json'},
url: '/api/myquiz/answers/'
}
Upvotes: 1