.Net core 3.0 API 不使用连字符绑定属性 [英] .Net core 3.0 API doesn't bind properties with hyphen

查看:13
本文介绍了.Net core 3.0 API 不使用连字符绑定属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因为上次没有收到很好的回复所以重新审核了这个问题.希望我提供了以下所有必需的信息.

我有一个基本的 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.

https://docs.microsoft.com/en-us/aspnet/core/migration/22-to-30?view=aspnetcore-3.1&tabs=visual-studio#newtonsoftjson-jsonnet-support

这篇关于.Net core 3.0 API 不使用连字符绑定属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆