[英]Can't bind json in POST request body to class argument in .net-core
I'm trying to make a post request from my Angular frontend to the .net Core 3.1 backend, but in the controller method the argument object only gets by default 0 and null values; I'm trying to make a post request from my Angular frontend to the .net Core 3.1 backend, but in the controller method the argument object only gets by default 0 and null values;
let response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(obj)
});
[ApiController]
[Route("[controller]")]
[ApiExplorerSettings(IgnoreApi = true)]
public class RequestController : ControllerBase
{
[HttpPost]
public async Task<IAResponseViewModel> PostAnswer([FromBody] IAResponseViewModel something)
{
var temp = something.ToString();
if (!ModelState.IsValid)
{
Console.WriteLine();
}
return something;
}
}
public class IAResponseViewModel
{
public string AdministrationId { get; }
public int RoundUsesItemId { get; }
public int ResponseOptionId { get; }
}
The JSON object I see being submitted我看到正在提交的 JSON object
{AdministrationId: "12345678-00e8-4edb-898b-03ee7ff517bf", RoundUsesItemId: 527, ResponseOptionId: 41}
When inspecting the controller method the 3 values of the IAResponseViewModel are null or 0 When I change the argument to object I get something with a value of检查 controller 方法时,IAResponseViewModel 的 3 个值是 null 或 0 当我将参数更改为 object 时,我得到的值为
ValueKind = Object : "{"AdministrationId":"12345678-00e8-4edb-898b-03ee7ff517bf","RoundUsesItemId":523,"ResponseOptionId":35}"
I've tried with and without the [FromBody] attribute, changing the casing of the properties of the controller method's argument and the frontend argument, copy pasting the viewmodel attributes on to the submitted object keys, wrapping the posted object in a 'something' object.我已经尝试使用和不使用 [FromBody] 属性,更改 controller 方法的参数和前端参数的属性的大小写,将 viewmodel 属性复制粘贴到提交的 object 键上,将发布的 ZA8Z6FDE6331C49EB666AC object。 the ModelState.IsValid attribute shows as true.
ModelState.IsValid 属性显示为真。 I've red other answers such as Asp.net core MVC post parameter always null & https://github.com/dotnet/aspnetcore/issues/2202 and others but couldn't find an answer that helped.
我有其他答案,例如Asp.net 核心 MVC 后参数总是 null和https://github.com/dotnet/aspnetcore/issues/2202和其他人找不到帮助的答案。
Why isn't the model binding working and how do I populate the viewmodel class I'm using with the json data?为什么 model 绑定不起作用,如何填充我正在使用 json 数据的视图模型 class?
From a comment on my original question:从对我原来的问题的评论:
Could it be because the properties in IAResponseViewModel are 'get only'?可能是因为 IAResponseViewModel 中的属性是“仅获取”吗?
Indeed this was the problem.确实这就是问题所在。 Giving the properties (default) set methods fixed the problem.
提供属性(默认)设置方法解决了这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.