使用Visual Studio 2019的ASP.NET Core Web Application模板(ASP.NET Core 3.1)创建Web Api项目,选择控制台方式(即使用.Net Core自带的Kestrel Web Server,而不是IIS Express)启动运行项目,默认响应报文如下:
HTTP/1.1 200 OK
Connection: close
Date: Sun, 24 May 2020 14:14:18 GMT
Content-Type: application/json; charset=utf-8
Server: Kestrel
Transfer-Encoding: chunked
[
{
"date": "2020-05-25T22:14:18.347603+08:00",
"temperatureC": 23,
"temperatureF": 73,
"summary": "Hot"
},
{
"date": "2020-05-26T22:14:18.3476146+08:00",
"temperatureC": -5,
"temperatureF": 24,
"summary": "Freezing"
},
{
"date": "2020-05-27T22:14:18.3476154+08:00",
"temperatureC": 53,
"temperatureF": 127,
"summary": "Chilly"
},
{
"date": "2020-05-28T22:14:18.3476156+08:00",
"temperatureC": -1,
"temperatureF": 31,
"summary": "Chilly"
},
{
"date": "2020-05-29T22:14:18.3476158+08:00",
"temperatureC": 10,
"temperatureF": 49,
"summary": "Bracing"
}
]
现在我想响应实体不再返回temperatureF字段,依据官方文档添加了常用的NewtonsoftJson包,并在相应字段加上[JsonIgnore] Attribute, 再次启动项目,发现没有起作用。
1 public void ConfigureServices(IServiceCollection services)
2 {
3 services.AddControllers().AddNewtonsoftJson();
4 }
1 using System;
2 using System.Text.Json.Serialization;
3
4 namespace WebApi
5 {
6 public class WeatherForecast
7 {
8 public DateTime Date { get; set; }
9
10 public int TemperatureC { get; set; }
11
12 [JsonIgnore]
13 public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
14
15 public string Summary { get; set; }
16 }
17 }
仔细检查发现WeatherForecast所引用的命名空间不正确,修改成using Newtonsoft.Json; 再次运行,达到了想要的效果。那么,用.NET core自带的System.Text.Json能否达到同样的效果呢?答案是肯定的。即创建完项目直接在TemperatureF添加[JsonIgnore] Attribute,并添加相应引用(using System.Text.Json.Serialization;)即可。
总结:.NET core自带的System.Text.Json和Newtonsoft.Json有同名的Attribute,如上面所说的JsonIgnore,在使用Newtonsoft.Json的时候要注意引用正确的包。