.net core webapi教程-设置返回Json格式与Model大小写一致
深山老妖浏览:11412023-11-30 08:09:28本文累计收益:0我也要赚钱

asp.net core webapi默认返回的json数据首字母都是小写的,本文讲解如何将webapi返回的json格式与Model字段的大小写一致。

新建一个.net core webapi项目,并新建一个用于返回的TestModel类。

namespace NetCoreStudy.Model
{
    public class TestModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public DateTime CreatedDate { get; set; }
    }
}

然后新增一个ValuesController。

using Microsoft.AspNetCore.Mvc;
using NetCoreStudy.Model;

namespace NetCoreStudy.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        [HttpGet]
        public string Test()
        {
            return "ok";
        }
        [HttpGet]
        public List<TestModel> GetTest()
        {
            var list = new List<TestModel>();
            list.Add(new TestModel() { Id = 123, Name = "张三", Description = "测试描述", CreatedDate = DateTime.Now });
            list.Add(new TestModel() { Id = 234, Name = "李四", Description = "测试描述", CreatedDate = DateTime.Now });
            return list;
        }
    }
}

项目代码截图如下:

运行项目返回Json格式如下:

从上图可以看到返回json数据首字母都是小写的,下面讲如何配置成大写的,首先导入Microsoft.AspNetCore.Mvc.NewtonsoftJson包。然后在Program.cs进行配置。代码如下:

builder.Services.AddControllers().AddNewtonsoftJson(options => {
    //配置返回Json大小写格式与Model一致
    options.SerializerSettings.ContractResolver = new DefaultContractResolver();
});
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

运行测试返回json格式如下:

至此配置已完成。

评论列表
发表评论
+ 关注