我正在编写一个WebAPICore来从数据库中返回JSON对象。由于未知原因,默认情况下,属性将以camelCase的形式返回。
我检查了SQL脚本,它确实为DataField返回了正确的大小写。但是当我使用该服务时,对象的属性会自动更改为camelCase。
例如, OfferingID 将作为 offeringID
返回现有的Return JSON对象
{
"offeringID": 120842,
"courseCode": "FLTE2A1F/1",
"courseName": "FLT - E2 Certificate in Skills for Working Life (Animals) (QCF)"
}
我想要返回的格式
{
"OfferingID": 120842,
"CourseCode": "FLTE2A1F/1",
"CourseName": "FLT - E2 Certificate in Skills for Working Life (Animals) (QCF)"
}
模特 - 提供:
public class Offering
{
[Key]
public int OfferingID { get; set; }
public string CourseCode { get; set; }
public string CourseName { get; set; }
}
我的WebAPI控制器获取方法
[HttpGet("{id}")]
public async Task<IActionResult> GetOfferingDetail(int id)
{
var obj = await _context.Offerings.FromSql("dbo.GetOfferingDetail @p0", id).SingleOrDefaultAsync();
if (obj == null)
return NotFound("ID not found");
return new ObjectResult(obj);
}
在Startup.cs中配置服务方法:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<DbContexts.OakCommonsDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("MyConnection")));
services.AddCors(options => options.AddPolicy("AllowAll", p => p.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()));
var mvccore = services.AddMvc();
mvccore.AddJsonOptions(o => o.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore);
}
你能否告诉我如何在模型中定义的确切案例中返回JSON对象?
答案 0 :(得分:0)
这是工作代码。默认情况下,WebAPI Core将使用CamelCasePropertyNamesContractResolver()。您需要将其更改为DefaultContractResolver以按照您在模型中定义的方式进行渲染。
DefaultContractResolver位于Newtonsoft.Json.Serialization名称空间下。
services.AddMvc()
.AddJsonOptions(o => o.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)
.AddJsonOptions(o => o.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver());