繁体   English   中英

将包含带有连字符的 Header 属性的请求绑定到 .Net Core 3.1 API

[英]Bind request containing Header property with Hyphens to .Net Core 3.1 API

引用.Net core 3.0 API 不会使用 hyphen 绑定属性,我尝试了 .NET Core 3.1 中的代码从头中接受带连字符的属性名称 (test-property) 并将其转换为我的类的内部名称 (testProperty)。 我正在使用 System.Text.Json。 这是我的代码:

    [HttpPut]
    public string Put([FromHeader]PostModel header)
    {
        return header.testProperty;
    }
    public class PostModel
    {
        [JsonPropertyName("test-property")]
        [FromHeader]
        [Required] 
        public string testProperty { get; set; }
    }

当我使用标头中的属性 test-property 调用 API 时,它返回验证错误“需要 testProperty 字段”。 当我更改标头以传入 testproperty 而不是 test-property 时,API 运行良好并返回始终有趣的字符串“Hello world”。 我觉得我错过了一些明显的东西,但我一生都无法弄清楚是什么。

JsonPropertyName指定序列化和反序列化时 JSON 中存在的属性名称。 如果您使用 json 从 body 发送数据,则效果很好。 您所做的是来自标题,您需要进行如下更改:

public class PostModel
{
    [JsonPropertyName("test-property")]
    [FromHeader(Name = "test-property")]
    [Required]
    public string testProperty { get; set; }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM