简体   繁体   中英

Method signature in ASP.NET Core for AngularJS API request with JSON

I have the following API request:

var answeredQuestions = {};
$scope.GetNextQuestion = function (question, value) {

    answeredQuestions[question] = value;
    var data = {
    };
    data["currentStep"] = $scope.currentStep;
    data["answeredQuestions"] = answeredQuestions;

    $http.post("/api/WizardAPI/GetNextQuestion", JSON.stringify(data))
        .then(function (data) {
            $scope.currentStep = data.data;
        }, OnError);
};

This is the API controller:

[HttpPost]
[Route("GetNextQuestion")]
public IActionResult GetNextQuestion([FromBody]string currentStep)
{
    return Ok("test");
}

However, "currentstep" is always empty. If I change the data type to object I get something, so the API call is working. I tried mapping it to a custom class, but then the API call fails.

Here's the class:

public class data
{
    public string CurrentStep { get; set; }
    public string[,] AnsweredQuestions { get; set; }
}

What is the best way to handle this JSON?

Request payload

{"currentStep":"ERP","answeredQuestions":{"ERP":1}}

As discussed based on your request payload, the AnsweredQuestions type should be: Dictionary<string, dynamic> .

And it is suggested to name the class as PascalCase as C# naming convention.

public class Data
{
    public string CurrentStep { get; set; }
    public Dictionary<string, dynamic> AnsweredQuestions { get; set; }
}

Change your GetNextQuestion API method as:

[HttpPost]
[Route("GetNextQuestion")]
public IActionResult GetNextQuestion([FromBody] Data data)
{
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM