I have a .NET Core Web API controller to handle a POST request which takes a JSON ApiUser object and also returns an ApiUser object
[HttpPost]
public ApiUser Post([FromBody] ApiUser model) {
return new ApiUser();
}
Let's say I want to return an error message to the client: "Email already exists." I don't know how best to do it in a simple manner.
I could add an "ErrorMsg" property to ApiUser (and every other class that I return through the API), but not sure if this is the correct way.
"Pre-Core", I'd throw a HttpResponseException, which is not supported in Core. This was nice because it would create a simple JSON with "Message" which I could then grab. (Goofy: I'd use status 202 Accepted as a flag to my client that we had a "known error".)
throw new HttpResponseException(request.CreateErrorResponse(HttpStatusCode.Accepted, msg));
(I think I'd prefer to deal with this inside the controller, instead of "filters" or "middleware". One concern with the latter two is that if I add razor pages, I assume I'd need to know if error came from api calls or from UI web calls.)
UPDATE #1
Seems I can do the following (return ActionResult< T>) to simulate what I did before with HttpResponseException. Still not sure if doing something like this or returning status 200 with adding ErrorMsg to ApiUser would be better.
[HttpPost]
public async Task<ActionResult<ApiUser>> Post([FromBody] ApiUser model) {
...
if (emailExists) return StatusCode(400, "Email already exists.");
else return user;
}
