c# - 使用 JsonProperty 将 JSON 绑定(bind)到模型属性

标签 c# json rest asp.net-web-api2

我受我方与客户之间的协议(protocol)约束,使用包含破折号的 json 参数。由于无法在 C# 的属性名称中使用它,因此我需要映射到所需的属性。

我现在做什么:

The below code is simplified for convenience.

型号

public class MyRequest
{
    [JsonProperty("request-number")]
    public string RequestNumber { get; set; }

    [JsonProperty("name")]
    public string Name { get; set; }
}

Controller

[HttpGet]
[Route("api/load-stuff")]
public Stuff LoadStuff([FromUri]MyRequest request)
{
    return BackEnd.LoadStuff(request);
}

从客户端调用 API

上面的 Controller 是使用这个 uri 定位的:

http://localhost:12345/api/load-stuff?request-number=X123&name=requestName

我的问题

如果我在 BackEnd.LoadStuff 行放置断点,我可以看到调用到达,但请求未正确映射。

Name contains what I expect: requestName, but RequestNumber is null, so the mapping didn't work.

出了什么问题?

最佳答案

ASP.NET 的默认模型绑定(bind)器在尝试将请求参数绑定(bind)到模型时不考虑 JsonPropertyAttribute(它不能,因为它不知道 JsonPropertyAttribute 和 NewtonSoft.Json 的其余部分)。鉴于您的情况(在 C# 中不是合法标识符的属性名称),实现您想要的唯一方法是通过 custom model binder确实读取 JsonPropertyAttribute

如果您确实拥有作为合法标识符的属性名称(例如 request_number),那么您可以使用这些命名属性创建请求模型,然后将其映射到具有正确命名属性的单独模型,例如:

public class MyController : ApiController
{
    [HttpGet]
    [Route("api/load-stuff")]
    public Stuff LoadStuff([FromUri]MyRequest request)
    {
        return BackEnd.LoadStuff(request.ToMyPrettyRequest());
    }
}

public class MyRequest
{
    public string request_number { get; set; }

    public string name { get; set; }

    MyPrettyRequest ToMyPrettyRequest()
    {
        return new MyPrettyRequest
        {
            RequestNumber = request_number,
            Name = name,
        };
    }
}

public class MyPrettyRequest
{
    public string RequestNumber { get; set; }

    public string Name { get; set; }
}

关于c# - 使用 JsonProperty 将 JSON 绑定(bind)到模型属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42020116/

相关文章:

c# - 将 unicode 字符的十六进制序列解码为字符串的最佳方法

c# - 如何在 C# 中动态更改 td 的 colspan?

c# - 具有数据绑定(bind)和常量字符串的 WPF 窗口标题

json - 将JSON文件解析为logstash

arrays - 如何使用PL/JSON解析数组数据

javascript - 从 Confluence 调用自定义 REST API

json - 如何使用curl 发布到REST/JSON 服务?

postgresql - Postgres View 在执行 SQL 时返回正确的行,但使用 REST 查询多次返回一行

c# - 如何使用 JSON.NET 的自定义引用解析

javascript - 使用 React 读取嵌套 JSON 数据