.Net core 3.0 API 不使用连字符绑定属性 [英] .Net core 3.0 API doesn't bind properties with hyphen
问题描述
因为上次没有收到很好的回复所以重新审核了这个问题.希望我提供了以下所有必需的信息.
我有一个基本的 API 控制器,但我的 Json 对象似乎没有正确绑定到模型.根对象绑定,但名称中带有连字符的属性不绑定.不幸的是,我无法删除属性名称中的连字符.
I have a basic API controller and my Json object doesn't seem to bind to the model properly. The root object binds but the property with hyphen in its name doesn't bind. Unfortunately, I cannot drop the hyphen in the property name.
如何让属性正确绑定?
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
namespace TestCoreAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class TestController : ControllerBase
{
// POST: api/Test
[HttpPost]
public string Post([FromBody] TestPayload testPayload)
{
if (testPayload == null)
{
return "Test payload is empty";
}
if (string.IsNullOrWhiteSpace(testPayload.TestProperty))
{
return "Test property is empty";
}
return "Valid input - " + testPayload.TestProperty;
}
}
[JsonObject("test-payload")]
public class TestPayload
{
[JsonProperty(PropertyName = "test-property")]
public string TestProperty { get; set; }
}
}
这是我对 API 的调用
This is the call I'm making to the API
POST /api/test HTTP/1.1
Content-Type: application/json
{"test-property":"some string value"}
推荐答案
您是否在 Startup.ConfigureServices
中将 AddNewtonsoftJson()
添加到您的服务中?如果不是,则使用新的 System.Text.Json
,而不是 Newtonsoft.我认为您需要执行 AddNewtonSoftJson()
因为我相当确定 System.Text.Json
不支持kebab case"绑定.
Are you adding AddNewtonsoftJson()
to your services in Startup.ConfigureServices
? If not, the new System.Text.Json
is being used, not Newtonsoft. I think you'll need to do AddNewtonSoftJson()
as i'm fairly sure System.Text.Json
doesn't support 'kebab case' bindings.
这篇关于.Net core 3.0 API 不使用连字符绑定属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!