[英]ASP.NET Core handling JSON deserialization problems
我想更改 ASP.NET 核心中無效 JSON 請求處理的默認行為。 我有這個 model:
public class Model
{
public Guid Id { get; set; }
}
當我用這個身體發送這個請求時
{
"Id": null
}
它返回此錯誤消息:
"Error converting value {null} to type 'System.Guid'. Path 'Id', line 2, position 11."
當然這絕對合乎邏輯,但我希望將 Id 設置為默認值 (Guid.Empty) 而不是失敗的請求。 我在啟動中添加了這個 json 配置:
services.AddMvc()
.AddJsonOptions(options => options.SerializerSettings.Error = (a, e) =>
{
e.ErrorContext.Handled = true;
})
錯誤處理程序被命中,但是 ASP.NET 核心仍然返回失敗。 與 ASP.NET Web API 相比,這在不同的行為中是可能的。
如您所見,此行為由 JsonInputFormatter 處理,您可以自定義格式化程序以覆蓋此行為,例如
IgnoreGuidErrorJsonInputFormatter
public class IgnoreGuidErrorJsonInputFormatter: JsonInputFormatter { public IgnoreGuidErrorJsonInputFormatter(ILogger logger, JsonSerializerSettings serializerSettings, ArrayPool<char> charPool, ObjectPoolProvider objectPoolProvider, MvcOptions options, MvcJsonOptions jsonOptions): base(logger, serializerSettings, charPool, objectPoolProvider, options, jsonOptions) { serializerSettings.Error = (a, e) => { var errors = e.ErrorContext.Error; e.ErrorContext.Handled = true; }; } }
注冊IgnoreGuidErrorJsonInputFormatter
services.AddMvc(options => { var serviceProvider = services.BuildServiceProvider(); var customJsonInputFormatter = new IgnoreGuidErrorJsonInputFormatter( serviceProvider.GetRequiredService<ILoggerFactory>().CreateLogger<IgnoreGuidErrorJsonInputFormatter>(), serviceProvider.GetRequiredService<IOptions<MvcJsonOptions>>().Value.SerializerSettings, serviceProvider.GetRequiredService<ArrayPool<char>>(), serviceProvider.GetRequiredService<ObjectPoolProvider>(), options, serviceProvider.GetRequiredService<IOptions<MvcJsonOptions>>().Value ); options.InputFormatters.Insert(0, customJsonInputFormatter); });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.