1

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;
}
1

1 Answer 1

6

You can use HttpResponseException in the core web api:

  [HttpPost]
        public ApiUser Post([FromBody] ApiUser model)
        {
            if (model.Email == "11")// this condition can be changed as your requirement.
            {
                var response = new HttpResponseMessage(HttpStatusCode.BadRequest);
                response.Content = new StringContent("Email already exists.");
                throw new HttpResponseException(response);
            }

            return new ApiUser();
        }

Here is the test result:

enter image description here

Update

You can also change return type as IActionResult to return different content as follow:

   [HttpPost]
        public IActionResult Post([FromBody] ApiUser model)
        {
            if (model.Email == "11")// this condition can be changed as your requirement.
            { 
                return BadRequest("Email already exists.");
            }

            return Ok(new ApiUser());
        }

The test result is the same as before.

Sign up to request clarification or add additional context in comments.

3 Comments

It does seem I can still use "HttpResponseException" if I install a package called "Microsoft.AspNet.WebApi.Core", but this hasn't been updated since 2018. I'm not sure this is the best solution. Great video. I just installed Postman to help me test this.
@ErnieThomason, if you don't want to use HttpResponseException, you can change your return type to IActionResult , as the method you update in your question, but there are some details to change ,I have updated in my post, you can follow it.
Thank you very much for your help. This gives me enough info on my options so I can move forward.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.