Search code examples
c#.netangular

ASP.NET API getting null as request body


I have my controller class as:

namespace air_bnb.Controllers
{
    [Route("api/[controller]")]
    public class UserController : Controller
    {
        private readonly UserDbContext context;
        private readonly IConfiguration _config;

        public UserController(IConfiguration configuration, UserDbContext _context)
        { 
            _config = configuration;
            context = _context;
        }

        [HttpPost("register")]
        public async Task<IActionResult> Register(LoginReqDto request)
        {
            System.Diagnostics.Debug.WriteLine(request.Password);
            var hashedPw = BCrypt.Net.BCrypt.HashPassword(request.Password);
            User createdUser = new User
                                   {
                                       Email = request.Email,
                                       Password = hashedPw,
                                       Id = Guid.NewGuid().ToString()
                                   };

            createdUser.Email = request.Email;
            createdUser.Password = hashedPw;

            await context.Users.AddAsync(createdUser);

            try 
            {
                await context.SaveChangesAsync(); 
            }
            catch (Exception e) 
            {
                return BadRequest(request.Password); 
            }

            return Ok(request.Password);
        }
    }
}

From the frontend, I am using HTTPClient in Angular. When I use Postman to send my data, everything works perfectly.


Solution

  • Is there any difference in the body data are you sending from the Angular app and Postman? Like using form data(application/x-www-form-urlencoded) or JSON(application/json).

    Here, you are using a Controller base class that default binds data from the from data. If you are passing data in the JSON format then you have to explicitly specify the [FromBody] attribute for the action parameter.

    public async Task<IActionResult> Register([FromBody] LoginReqDto request)