ASP.NET Web API如何返回带空格属性名的JSON响应
实现ASP.NET Web API返回带空格的JSON属性名
你遇到的问题核心是JSON序列化器与特性不匹配,以下分两种常见场景给出解决方案:
场景1:使用ASP.NET Core默认的System.Text.Json
ASP.NET Core 3.0及以上默认使用System.Text.Json序列化,此时需要用System.Text.Json.Serialization命名空间下的[JsonPropertyName]特性,而非Newtonsoft的[JsonProperty]:
using System.Text.Json.Serialization; public class MyApp { public int AppId { get; set; } [JsonPropertyName("App Name")] public string AppName { get; set; } }
修改后重新运行API,即可返回带空格的属性名。
场景2:使用Newtonsoft.Json(Json.NET)
如果你的项目配置了使用Newtonsoft.Json(比如老版ASP.NET Web API,或ASP.NET Core中手动切换了序列化器),需要确保两点:
- 模型中使用Newtonsoft的
[JsonProperty]特性(你之前的写法是对的):
using Newtonsoft.Json; public class MyApp { public int AppId { get; set; } [JsonProperty(PropertyName = "App Name")] public string AppName { get; set; } }
- 确保项目已配置启用Newtonsoft.Json序列化:
- 对于ASP.NET Core项目,在
Program.cs中添加配置:
builder.Services.AddControllers() .AddNewtonsoftJson();- 对于老版ASP.NET Web API(Framework),默认已使用Newtonsoft.Json,无需额外配置,若未生效可检查是否有自定义序列化配置覆盖了特性。
- 对于ASP.NET Core项目,在
验证
修改完成后,重新启动API,用Postman请求对应接口,即可得到如下响应:
[ { "appId": 1, "App Name": "app1" }, { "appId": 2, "App Name": "app2" } ]
内容的提问来源于stack exchange,提问作者Sayan
相关产品推荐
相关产品推荐

