我正在使用 System.Text.Json.Serialization,为什么查询参数会忽略 [JsonPropertyName]

问题描述 投票:0回答:1

我正在使用

System.Text.Json.Serialization
并且我有一个用于查询的类。在本课程中,我将
JsonPropertyName
属性自定义为
"site"

public class SearchQuery
{
    [JsonPropertyName("site")]
    public string SiteName { get; set; }
}

我的预期行为是当我点击 URL 时:

https://example.com/search?site=sandbox

query.SiteName
"sandbox"
。但是,
[JsonPropertyName("site")]
会被忽略。当前的行为是仅当我点击 URL 时:

https://example.com/search?siteName=sandbox

query.SiteName
"sandbox"

有没有办法使用

System.Text.Json.Serialization
自定义查询参数中的属性名称?

c# .net serialization system.text.json
1个回答
1
投票

更改查询字符串参数的名称与 json 无关。

您需要应用

FromQuery
属性并设置其
Name
属性。

public class SearchQuery
{
    [FromQuery(Name = "site")]
    public string SiteName { get; set; }
}
© www.soinside.com 2019 - 2024. All rights reserved.