I am using React Js in my client-side and.Net Core 3.0 Web API on the server-side. I have one API method called CreateAccount and the return type is IActionResult. Now if I do validate with any one of the model property then I have to send or return the validation message along with empty model data. I am new to API and tried like below but could not send the string as a result type.
API method,
[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();
}
I do not know the proper.Net Core API coding part, could anyone please help me to resolve this issue?
You could return an ObjectResult
with a StatusCode
other than StatusCodes.Status200OK
and a serialized object that contains whatever information you want to return to the client, eg:
return new ObjectResult(new YourApiError() { Message = "message.." })
{
StatusCode = StatusCodes.Status405MethodNotAllowed
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.