gpt4 book ai didi

使用 POSTMAN 客户端的 C# web API POST JSON 数据在 FromBody 中始终为 NULL

转载 作者:太空宇宙 更新时间:2023-11-03 12:39:05 28 4
gpt4 key购买 nike

我有一个包含模型的 Web Api -

 public class Assessments
{
public List<AssessmentResult> Results { get; set; }
}

public class AssessmentResult
{
public int? AssessorId { get; set; }
public int? AssessmentId { get; set; }
public int? CentreId { get; set; }
public int? BatchId { get; set; }
public DateTime AssessmentDate { get; set; }

和 Controller -

[HttpPost]
[ActionName("SetAssessmentResults")]
public HttpResponseMessage SetAssessmentResults([FromBody] Assessments assessments)
{
try
{

string sproc = ConfigurationManager.AppSettings["ASSESSORAPP_InsertAssessmentsStaging"];
//_dt = Helper.ToDataTable(assessments); use this if sending list doesnt work

Mapper.Initialize(cfg =>
{
//cfg.CreateMissingTypeMaps = false;
cfg.CreateMap<AssessmentResult, AssessmentTable>().IgnoreAllNonExisting();

//cfg.IgnoreUnmapped();
});
List<AssessmentTable> assessmentTable = Mapper.Map<List<AssessmentResult>, List<AssessmentTable>>(assessments.Results);
Mapper.Configuration.AssertConfigurationIsValid();

string isSuccess = _db.InsertAssessmentResults(sproc, assessmentTable);
if (isSuccess.Split('$')[0].ToLower() == "success")
{
return Request.CreateResponse(HttpStatusCode.OK, isSuccess);
}
else if (isSuccess.Split('$')[0].ToLower() == "duplicate")
{
return Request.CreateResponse(HttpStatusCode.OK, isSuccess);
}
else
{
return Request.CreateResponse(HttpStatusCode.OK, isSuccess);
}
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.InternalServerError, ex);
}
}

客户端,我使用的是 Postman Chrome 扩展程序。我正在发送正文中包含 JSON 数据的 POST 请求。但是,我没有在 Controller 中获取 JSON 数据(评估对象始终显示 NULL 值)

assessments object showing NULL value

在客户端,我请求使用 PostMan Chrome 扩展

PostMan Client sending request

这是我的 JSON 数据:

    {
"assessment":
[{
"AssessorId": 3,
"AssessmentId": 123,
"CentreId": 1,
"BatchId": null,
"AssessmentDate": "2016-09-30T00:00:00",

},{
"AssessorId": 2,
"AssessmentId": 123,
"CentreId": 1,
"BatchId": null,
"AssessmentDate": "2016-09-30T00:00:00",
}]
}

我还添加了 Content-Type : application/json

请帮我解决这个问题。谢谢!

最佳答案

在您的类(class)Assessments中,您将包含 AssessmentResult 列表的属性命名为“Results”,但是当您发送帖子时,您将属性命名为“assessment "它应该是 "Results"(考虑到您有默认的序列化程序配置,例如:序列化时没有属性名称到小驼峰大小写)

尝试:

  {
"Results":[{
"AssessorId": 3,
"AssessmentId": 123,
"CentreId": 1,
"BatchId": null,
"AssessmentDate": "2016-09-30T00:00:00",

},
{
"AssessorId": 2,
"AssessmentId": 123,
"CentreId": 1,
"BatchId": null,
"AssessmentDate": "2016-09-30T00:00:00",
}]
}

另外,作为一种好的做法,您应该在类的构造函数中实例化列表例如:

public class Assessments
{
public Assessments()
{
Results = new List<AssessmentResult>();
}
public List<AssessmentResult> Results { get; set; }
}

关于使用 POSTMAN 客户端的 C# web API POST JSON 数据在 FromBody 中始终为 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39748574/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com