shreesharao / aspnetcore-ConsoleToWeb

Convert Console project to web project for understanding the working of asp.net core mvc
0 stars 0 forks source link

400 bad request -When calling asp-net-core webapi #15

Open shreesharao opened 5 years ago

shreesharao commented 5 years ago

When calling the API -

[AllowAnonymous]
        [HttpPost("register")]
        public IActionResult Register([FromBody]UserDto userDto)
        {
            //map dto to entity
            var user = _mapper.Map<User>(userDto);

            try
            {
                // save 
                _userService.Create(user, userDto.Password);
                return Ok();
            }
            catch (AppException ex)
            {
                // return error message if there was an exception
                return BadRequest(new { message = ex.Message });
            }

        }

I am getting 400 bad request.

shreesharao commented 5 years ago

Check - https://stackoverflow.com/questions/51730845/400-the-input-was-not-valid-when-calling-asp-net-core-web-api

ModelState is only validated if it's able to successfully deserialize the post body/bind.

You were not specific in your question, but it sounds as if you're posting as x-www-form-urlencoded. If that's the case, you should not have [FromBody]. However, bear in mind that it's an either/or situation, so if you want to eventually post via JSON, then you should keep the attribute and post JSON from Postman instead.

Aside from that, ensure that you're either not using antiforgery token validation or that you are posting a valid token along with the request. Failing antiforgery validation will short circuit the request and return a 400 immediately.

If you are posting JSON, ensure that your JSON is valid. If the JSON is invalid, you'll get a 400 immediately.