亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

C# ASP.NET 錯誤響應不使用 GlobalConfiguration

C# ASP.NET 錯誤響應不使用 GlobalConfiguration

C#
DIEA 2021-10-09 19:40:19
我在用.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 回答

  • 1 回答
  • 0 關注
  • 321 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號