1

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?

0

1 Answer 1

1

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, e.g.:

return new ObjectResult(new YourApiError() { Message = "message.." })
{ 
     StatusCode = StatusCodes.Status405MethodNotAllowed 
};
Sign up to request clarification or add additional context in comments.

5 Comments

What I should give for the "YourApiError"?
@MdAslam: It's a simple POCO class with a Message property that you define yourself: public class YourApiError { public string Message { get; set; } }
Yeah thank you for that but I wanted to check the result also. If the result is proper then I have to send the result with statusCode but If any error in the service class then I have to return the validation message. So I have to do it with implicit logic? See my code again that if(user.UserType!="Admin") { return new ValidationResult("Only Admin can create new account"); }
@MdAslam: I am not sure I understand your issue. Of course you need to return a different kind of result based on the outcome of your controller action's validation logic.
Why we can not use the HttpResponseMessage in .Net Core? I think by using this return type "HttpResponseMessage", we can send either error message or success message along with our model data, so I tried to use this HttpResponseMessage but not able to create the response. Can you help on this if any idea on HttpResponseMessage?

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.