我在用.NET 框架 4.6.1微軟.AspNet.WebApi 5.2.4ASP.NET 使用 Newtonsoft.Json 11.0.2在Global.asax我指定我想使用 SnakeCaseNamingStrategy 進行我的 JSON 序列化:public class WebApiApplication : System.Web.HttpApplication{ protected void Application_Start() { ... var formatters = GlobalConfiguration.Configuration.Formatters; // Remove the xmlformatter formatters.Remove(formatters.XmlFormatter); // Ignore reference loops formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; // Use snake_case formatters.JsonFormatter.SerializerSettings.ContractResolver = new DefaultContractResolver() { NamingStrategy = new SnakeCaseNamingStrategy() }; }}這在返回OK和大多數其他成功指示狀態代碼(200-300)時效果很好:[HttpGet, Route("api/Test")]public IHttpActionResult Test(){ return Ok(new { Message = "Hello World!" });}返回:{ "message": "Hello World!"}但是,當返回任何錯誤代碼或異常時,ASP.NET 似乎會忽略任何格式化程序設置:[HttpGet, Route("api/Test")]public IHttpActionResult Test(){ return BadRequest("Hello World!");}返回:{ "Message": "Hello World!" // 'Message' is not snake_case}和[HttpGet, Route("api/Test")]public IHttpActionResult Test(){ var runtimeErroredArray = new int [2]; runtimeErroredArray[2] = 5; // runtime error return Ok();}返回:{ "Message": "An error has occurred.", "ExceptionMessage": "Index was outside the bounds of the array.", // Should be 'exception_message' "ExceptionType": "System.IndexOutOfRangeException", // "System.IndexOutOfRangeException" can stay the same obviously, but 'ExceptionType' should be 'exception_type' "StackTrace": "---"}我不明白為什么會發生這種情況,但我主要想知道如何解決它。問題:有沒有辦法可以強制異常消息和錯誤代碼消息遵循GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ContractResolver我在Global.asax(使用SnakeCaseNamingStrategy)中設置的?
- 1 回答
- 0 關注
- 321 瀏覽
添加回答
舉報
0/150
提交
取消