Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading