我在用
.NET 框架 4.6.1
微软.AspNet.WebApi 5.2.4
ASP.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)中设置的?
相关分类