2016-03-03 170 views
21

試圖設置JsonOutputFormatter選項:JsonSerializerSettings和Asp.Net核心

var jsonFormatter = (JsonOutputFormatter) options.OutputFormatters.FirstOrDefault(f => f is JsonOutputFormatter); 
if (jsonFormatter != null) 
{ 
    jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); 
} 

mvcBuilder.AddJsonOptions(jsonOptions => 
    { 
     jsonOptions.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); 
    }); 

但只要我添加此,我得到:

MissingMethodException:方法未找到:' Newtonsoft.Json.JsonSerializerSettings Microsoft.AspNet.Mvc.Formatters.JsonOutputFormatter.get_SerializerSettings()'。

我使用的是標準的Microsoft.AspNet.Mvc.Formatters.Json (6.0.0-rc1-final)

編輯:通過安裝Newtonsoft.Json 6.0.6(該降級的所有其他引用)解決它

任何人都得到一個已經? 謝謝..

+1

凡你想插入代碼片段?什麼是'mvcBuilder'?你可以在'Startup.cs'中包含'ConfigureServices'方法的代碼嗎?這是調用AddJsonOptions的正確位置。 – Oleg

+0

這只是今天隨機發生的事情。老實說,它昨天正在工作,這真的讓我感到困惑。 –

回答

1

我假設你正在使用ASP.Net的核心,你應該使用 「Microsoft.AspNetCore.Mvc」:此

"Microsoft.AspNet.Mvc": "6.0.0-rc1-final" 

所以更換此

"Microsoft.AspNetCore.Mvc": "1.0.0-rc2-final" 
42

.Net Core 1.0 RTM自帶的CamelCase格式化開箱即用。這是來自RC2的行爲change。但是,如果需要修改它,試試這個片斷:

services.AddMvc() 
     .AddJsonOptions(opt => 
    { 
     var resolver = opt.SerializerSettings.ContractResolver; 
     if (resolver != null) 
     { 
      var res = resolver as DefaultContractResolver; 
      res.NamingStrategy = null; // <<!-- this removes the camelcasing 
     } 
    }); 

更多信息here

對於DOTNET核心1.0.1:

services 
      .AddMvcCore() 
      .AddJsonFormatters(o => o...); 
+1

非常感謝!我無法弄清楚自動駱駝套在哪裏發生。 –

+4

任何想法.net核心1.1中的這個調用是什麼? –

+0

@LeviFuller它是一樣的 - 'AddJsonOptions' – chester89