繁体   English   中英

ASP.NET Core 中使用 JSON 的 AngularJS API 请求的方法签名

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

我有以下 API 请求:

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

这是 API 控制器:

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

但是,“currentstep”始终为空。 如果我将数据类型更改为对象,我会得到一些东西,所以 API 调用正在工作。 我尝试将其映射到自定义类,但 API 调用失败。

这是课程:

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

处理这个 JSON 的最佳方法是什么?

请求有效载荷

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

正如根据您的请求负载所讨论的那样, AnsweredQuestions类型应为: Dictionary<string, dynamic>

并且建议将类命名为 PascalCase 作为 C# 命名约定。

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

将您的GetNextQuestion API 方法更改为:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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