2017-05-03 42 views
0

我有以下型號的Json屬性空 - ASP.NET核心

public class SocioEconomicStudy : BaseModel 
{ 
    public string Folio { get; set; } 

    public string Craft { get; set; } 

    public string RequestType {get;set;} 
} 

我送以下JSON

{ 
    "folio" : "folio", 
    "craft" : "craft, 
    "request_type": "request_type" 
} 

但與下劃線收到的屬性爲null,我已經試過駱駝案件帕斯卡案件,但只有小寫+下劃線是沒有下劃線的屬性工作。

控制器的方法:

[HttpPost] 
public void Post([FromBody] SocioEconomicStudy study) 
{ 
    var cancellationToken = new CancellationToken(); 
    _logger.LogInformation((study != null).ToString()); 
    _context.SocioEconomicStudyRepository.AddAsync(study, cancellationToken); 
} 

因此,只有沒有下劃線的屬性依然存在,如何解決這個任何想法?

+1

你使用什麼json serializer? –

+0

@RubenVardanyan我正在使用默認序列化程序 –

+0

請參閱下面的回答 –

回答

0

加入以下Startup.cs解決我的問題

services.AddMvc() 
     .AddJsonOptions(options => 
     { 
      options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver(); 
     }); 

屬性現在它接受camelCase密鑰

2

對於那些不符合命名規則,你可以添加JsonProperty屬性,你的情況你的模型應該像這樣

public class SocioEconomicStudy : BaseModel 
{ 
    public string Folio { get; set; } 

    public string Craft { get; set; } 

    [JsonProperty("request_type")] 
    public string RequestType { get; set; } 
} 
+0

謝謝,但是如果我的模型改變了,或者我需要更多模型,我還需要使用多個單詞註釋每個屬性。 –

+0

是的,您需要註釋每個屬性或更改前端部分以發送名爲camel case的屬性 –