JSON 不使用 JsonProperty 名称的对象模型

JSON object model not utilizing JsonProperty names

如何让组件工厂在对 Razor 操作结果的 AJAX 请求中绑定并解析为 JSON 属性 属性名称? 现在,我有一个解决方法,我只发送 JSON 字符串并在服务器端反序列化它,但我认为必须有一种方法可以让操作做到这一点。

比如我有以下模型:

public class ExampleClass 
{
    [JsonProperty("@first-name")]
    public string FirstName { get; set; }

    [JsonProperty("@last-name")]
    public string LastName { get; set; }
}

然后,我尝试使用以下脚本发送我的模型(请注意,我已经删除了用于 razor 视图模型绑定的双“@@”以避免混淆)。这是“呈现”的脚本:

var model = {
        "@first-name": "test",
        "@last-name": "test"
    };

    $.ajax({
        url: '/Dashboard?handler=test',
        type: "POST",
        contentType: "application/json",
        data: JSON.stringify(model),
        beforeSend: function (xhr) {
            xhr.setRequestHeader("RequestVerificationToken", $('input:hidden[name="__RequestVerificationToken"]').val());
        },
        success: function (result) {

        },
        error: function (result) {
        }
    });

然后在我的处理程序上,我得到一个空对象(模型值为空)

public IActionResult OnPostTest([FromBody] ExampleClass model)

如果我将模型更改为以下,一切正常:

var model = {
        "FirstName": "test",
        "LastName": "test"
    };

我可以看到对象正在正确传递

我犯了一个愚蠢的错误...我使用的是 Newtonsoft.Json 库属性 属性 绑定 (JsonProperty),而不是 [=16] 中的操作 (JsonPropertyName) 使用的序列化器工厂=] ...非常愚蠢的时刻。意识到一旦我删除了 Newtonsoft 导入并看到我的 class 现在有错误,

正在工作中...

public class ExampleClass 
{
    [JsonPropertyName("@first-name")]
    public int FirstName { get; set; }

    [JsonPropertyName("@last-name")]
    public int LastName { get; set; }
}