[英].Net Core Web API: How to return a validation message from API method?
我在客戶端使用 React Js,在服務器端使用 .Net Core 3.0 Web API。 我有一個名為 CreateAccount 的 API 方法,返回類型是 IActionResult。 現在,如果我確實使用 model 屬性中的任何一個進行驗證,那么我必須發送或返回驗證消息以及空的 model 數據。 我是 API 的新手,並嘗試如下,但無法將字符串作為結果類型發送。
API方法,
[AllowAnonymous]
[HttpPost("createaccount")]
public async Task<IActionResult> CreateAccount([FromBody]Users user)
{
try
{
if (ModelState.IsValid)
{
if (user == null)
return BadRequest(new { message = "Data is empty" });
if(user.UserType!="Admin")
{
return new ValidationResult("Only Admin can create new account");
}
return Ok(await _userService.CreateAnUserAccount(user));
}
}
catch(Exception e)
{
throw new ArgumentException(e.Message);
}
return ValidationProblem();
}
我不知道正確的.Net Core API 編碼部分,誰能幫我解決這個問題?
您可以返回帶有StatusCode
以外的StatusCodes.Status200OK
的ObjectResult
和包含您想要返回給客戶端的任何信息的序列化 object,例如:
return new ObjectResult(new YourApiError() { Message = "message.." })
{
StatusCode = StatusCodes.Status405MethodNotAllowed
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.