首页 > 解决方案 > 属性名称包含下划线的 JsonProperty 返回 null

问题描述

我正在使用 MVC C#4、.NET 4.5.2。我正在尝试向我的路由发送 Postman 请求,但是带有下划线名称的 json 属性使方法中的请求属性返回 null。

json请求

{
    {
        "channel": "/api/v5",
        "action": "added",
        "resource_id": "d5276373-a975-43d5-a361-6947b20bb666",
        "app_user_auth": {
            "access_token": "78505b15-3c46-4287-8658-f52238b94724",
            "token_type": "Bearer",
            "expires_in": 300,
            "user_id": "7e575bd7-3a4a-46bd-b449-c99d919de8534",
            "organization_id": "a5f832fa-6226-4a6f-a7ff-b75758fd57ed"
        }
    }
}

请求.cs

[JsonObject]
public class Request
{
    [JsonProperty("channel")]
    public string Channel { get; set; }
    [JsonProperty("action")]
    public string Action { get; set; }
    [JsonProperty("resource_id")]
    public string ResourceId { get; set; }
    [JsonProperty("app_user_auth")]
    public AppUserAuth AppUserAuth { get; set; }
}

[JsonObject]
public class AppUserAuth
{
    [JsonProperty("access_token")]
    public string AccessToken { get; set; }
    [JsonProperty("token_type")]
    public string TokenType { get; set; }
    [JsonProperty("expires_in")]
    public int ExpiresIn { get; set; }
    [JsonProperty("user_id")]
    public string UserId { get; set; }
    [JsonProperty("organization_id")]
    public string OrganizationId { get; set; }
}

控制器.cs

[System.Web.Mvc.Route("webhook")]
[System.Web.Http.HttpPost]
public void WebHook([FromBody]Request request)
{
}

但这里的要求是

Action: "added"
AppUserAuth: null
Channel: "/api/v5"
ResourceId: null

我在这里想念什么?

标签: c#jsonasp.net-mvc

解决方案


默认使用 Newtonsoft.Json。
在 .NET Core 中包含 NuGet 包 Microsoft.AspNetCore.Mvc.NewtonsoftJson 并添加

services.AddControllers().AddNewtonsoftJson();

ConfigureServicesStartup.cs 中。

选择适用于您的 .NET 版本的软件包版本


推荐阅读