假設我PotatoController在我的 .NET Core 3.1 web 應用程式中作為 api 作業有這個操作:
[HttpPost]
public async Task<IActionResult> CreatePotatoAsync([FromBody] Potato potato)
{
// Code to create potato
}
現在讓我們假設用戶在嘗試創建一個新的土豆時,發送無效的 json,如下所示:
{
"potatoName": "testPotato",
"potatoAge": 7,
}
我的 api 不是從System.Text.Json庫中回傳一個丑陋的 500 錯誤,而是一個由我創建的漂亮的自定義 400的最佳方法是什么?
uj5u.com熱心網友回復:
當我創建一個 .Net 3.1 測驗 API 專案并使用您發布的代碼時,我得到的回應是帶有此正文的 400 BadRequest 回應:
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "|57182e0e-445086f96bddb4e8.",
"errors": {
"$.potatoAge": [
"The JSON object contains a trailing comma at the end which is not supported in this mode. Change the reader options. Path: $.potatoAge | LineNumber: 3 | BytePositionInLine: 0."
]
}
}
當我取消[ApiController]屬性時,我得到一個空的 Potato 物件。我無法復制您從 System.Text.Json 獲取 500 的行為
因此,它似乎可以立即滿足您的要求。您是否使用自定義 JSON 序列化程式或其他模型系結選項?你能發布更多你的代碼嗎?
uj5u.com熱心網友回復:
我更喜歡回傳 200 并在應用程式級別處理錯誤
如果我不需要回傳任何值
{
"status": "ok"
}
如果我需要回傳一個值
{
"status": "ok",
"result": [
{
"Name": "Fabio"
},
{
"Name": "Laura"
}
]
}
萬一發生錯誤
{
"status": "ko",
"exceptionMessage": "Something went wrong!"
}
考慮在控制器的基類中包含以下方法
/// <summary>
/// Processes the request using a method that does not return any value
/// </summary>
/// <param name="action">The method to be used to process the request</param>
protected JsonResult ProcessRequest(Action action)
{
return ProcessRequest(() =>
{
action();
return null;
});
}
/// <summary>
/// Processes the request using a method that returns a value
/// </summary>
/// <param name="func">The method to be used to process the request</param>
protected JsonResult ProcessRequest(Func<object> func)
{
JsonResult jsonResult = new JsonResult();
try
{
object result = func();
if (result != null)
{
jsonResult.Data = new { status = "ok", result = result, };
}
else
{
jsonResult.Data = new { status = "ok", };
}
}
catch (Exception e)
{
string message = e.Message;
jsonResult.Data = new { status = "ko", exceptionMessage = message, };
}
return jsonResult;
}
那么您的操作方法將如下所示
public ActionResult DoThat()
{
return ProcessRequest(() =>
{
// Do something
});
}
public ActionResult ReturnPersonList()
{
return ProcessRequest(() =>
{
return new List<Person> { new Person { Name = "Fabio" }, new Person { Name = "Laura" } };
});
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/381413.html
上一篇:.Net6控制臺應用程式:WebApplication.CreateBuilder與Host.CreateDefaultBuilder
