Dis*_*ame 0 .net c# api json .net-core
由于上次没有收到很好的答复,因此重新审查了该问题。希望我已提供以下所有必需信息。
我有一个基本的 API 控制器,我的 Json 对象似乎没有正确绑定到模型。根对象已绑定,但名称中带有连字符的属性未绑定。不幸的是,我无法删除属性名称中的连字符。
如何让属性正确绑定?
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; }
}
}
Run Code Online (Sandbox Code Playgroud)
这是我对 API 的调用
POST /api/test HTTP/1.1
Content-Type: application/json
{"test-property":"some string value"}
Run Code Online (Sandbox Code Playgroud)
Net Core 3.1 确实绑定连字符。无论哪种方式,这两个选项都是Newtonsoft.Json或 new-in-core-3 System.Text.Json,并且它们使用的Attribute名称略有不同:
public class PostModel
{
//This one if you are using Newtonsoft.Json
//The Nuget dependency is Microsoft.AspNetCore.Mvc.NewtonsoftJson
[JsonProperty(PropertyName = "kebab-case-json-field")]
//This one of you are using the new System.Text.Json.Serialization
[JsonPropertyName("kebab-case-json-field")]
public string kebabCaseProperty { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
同时,在您的 中Startup.cs,要使用 Newtonsoft,您需要AddMvc(),而对于新的 System.Text.Json 则不需要。这些都对我有用:
public void ConfigureServices(IServiceCollection services)
{
//if using NewtonSoft
services.AddMvc().AddNewtonsoftJson();
//if using System.Text.Json.
//This is the code that core 3 `dotnet new webapi` generates
services.AddControllers();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3092 次 |
| 最近记录: |