我们用ASP.NET Core开发Web API时,肯定会有返回值场景,ASP.NET Core则提供了三种返回类型:

特定类型

特定类型就是我们一般的数据类型或者自定义的类content-type的类型,还是拿之前的例子来说,如:

1
2
3
4
5
6

[HttpGet("all")]
public async Task<List> GetAllOrders()
{
    _logger.LogInformation("查询所有订单!");
    return await _context.Orders.ToListAsync();
}

我们可以看到,结果返回的是标准的JSON数组格式。特定类型简单,但是过于单一,有时候,我们想要返回一些其他状态类型的结果,这种方式便不可取了。

我们在用VS创建控制器时,选择包含读/写操作的API控制器时,VS会根据模板生成相应的代码,如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43

[HttpGet("{id}")]
       public async Task<ActionResult> GetOrder(long id)
       {
           var order = await _context.Orders.FindAsync(id);
           if (order == null)
           {
               return NotFound();
           }
           return order;
       }
       // PUT: api/Orders/5
       // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
       [HttpPut("{id}")]
       public async Task PutOrder(long id, Order order)
       {
           if (id != order.Id)
           {
               return BadRequest();
           }
           _context.Entry(order).State = EntityState.Modified;
           try
           {
               await _context.SaveChangesAsync();
           }
           catch (DbUpdateConcurrencyException)
           {
               if (!OrderExists(id))
               {
                   return NotFound();
               }
               else
               {
                   throw;
               }
           }
           return NoContent();
       }

我们从自动生成的代码中可以看出,在有返回值时,用的是,不需要返回值的方法则使用的,方法内部的返回值类型也比较多,如、、等,它们其实都继承了和,默认返回的-type类型是/json; =utf-8。

响应数据的格式

在 ASP.NET Core 3.0之后,默认是基于 .Text.Json来格式化JSON,默认格式为(驼峰命名法),如果想要设置为格式,那么需要在.cs进行设置

1

builder.Services.AddControllers().AddJsonOptions(options => options.JsonSerializerOptions.PropertyNamingPolicy = null);

content-type的类型_类型介绍_类型是什么意思

类型介绍_类型是什么意思_content-type的类型

在ASP.NET Core 6.0中默认使用的是.Text.Jsoncontent-type的类型,如果想换成.Json怎么弄呢?需要安装..Mvc.,然后去.cs中配置

1
2
3
4

builder.Services.AddControllers().AddNewtonsoftJson(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver()
{
    NamingStrategy = new DefaultNamingStrategy()
});

换成后,之前的便不再适用了,需要在类进行设置

类型是什么意思_content-type的类型_类型介绍

类型是什么意思_content-type的类型_类型介绍

在ASP.NET Core中,默认 支持 /json、text/json 和 text/plain 媒体类型,

类型是什么意思_content-type的类型_类型介绍

服务端会根据请求头中的标识中的类型作出相应的格式返回,默认是/json,如果我们想要支持XML怎么弄呢?很简单,只需要在.cs添加即可

content-type的类型_类型介绍_类型是什么意思

content-type的类型_类型是什么意思_类型介绍

如果你觉得现有的格式还是不足以支撑你现在有业务,别担心,ASP.NET Core提供自定义格式化,分别新建继承和类,重写父类的、、、nc方法,然后将自定义的格式化类在.cs中的添加到或,如

类型是什么意思_content-type的类型_类型介绍

好了,今天大概的了解了ASP.NET Core响应数据的格式,下一节,继续学习一下处理 ASP.NET Core Web API 中的错误

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注