问题是,当输入方法时,“会话”为空。如您所见,标头和​​JSON对象是正确的。你能告诉我我在做什么错吗?

我的POST请求与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();
            });
    }


和C#代码:

    [Route("answers")]
    [HttpPost]
    public IActionResult AnswerPost([FromBody] string session) {

       ...

    }


Chrome控制台:



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"

最佳答案

您正在将对象发布到WebApi:

var data = { "session": session };


这样就意味着您正在传递具有会话属性的对象。您告诉WebApi方法期望的是一个字符串:

public IActionResult AnswerPost([FromBody] string session)


不是一个对象。
我想如果您将代码更改为此:

$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();
            });
    }


它应该工作。希望这可以帮助。如果将来您要向函数传递更多参数,我将创建一个C#对象以传递给控制器​​。像这样:

public class AnswerPost
{
  public string Session {get; set;}
}


然后更新控制器方法,如下所示:

[Route("answers")]
    [HttpPost]
    public IActionResult AnswerPost([FromBody] AnswerPost answerpost) {
...
}

关于c# - Web API 2 POST请求返回null,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30574427/

10-10 13:33