2

I'm trying to post some form data to a .Net Core Web Api with React using fetch. I am able to hit the breakpoint inside the controller action, but the post data is always null. Any ideas why?

Register.js

import React, { Component } from 'react';

export class Register extends Component {
static displayName = Register.name;

constructor(props) {
    super(props);
    this.state = {
        userName: '',
        password: '',
        confirmPassword: ''
    };

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
}

handleChange(event) {
    this.setState({
        [event.target.name]: event.target.value
    });
}

handleSubmit(event) {
    event.preventDefault();
    let formData = new FormData();
    formData.append("UserName", this.state.userName);
    formData.append("Password", this.state.password);
    formData.append("ConfirmPassword", this.state.confirmPassword);
    
    fetch("api/account/register", {
        method: "POST",
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(formData)
    }).then(response => response.json())
        .then(data => console.log(data));
}

render () {
    return (
        <div>
            <h1>Register</h1>
            <form onSubmit={this.handleSubmit}>
                <div className="mb-3">
                    <label for="username" className="form-label">UserName</label>
                    <input type="text" className="form-control" name="userName" value={this.state.userName} onChange={this.handleChange} />
                </div>
                <div className="mb-3">
                    <label for="password" className="form-label">Password</label>
                    <input type="password" className="form-control" name="password" value={this.state.password} onChange={this.handleChange} />
                </div>
                <div className="mb-3">
                    <label for="confirmPassword" className="form-label">Confirm Password</label>
                    <input type="password" className="form-control" name="confirmPassword" value={this.state.confirmPassword} onChange={this.handleChange} />
                </div>
                <button type="submit" className="btn btn-primary">Submit</button>
            </form>
        </div>
    );
  }
}

AccountController.cs

[ApiController]
[Route("api/[controller]")]
public class AccountController : ControllerBase
{
    [HttpPost]
    [Route("register")]
    public IActionResult Register([FromForm] RegisterRequest request)
    {
        return Content("Controller call successful");
    }
}

public class RegisterRequest
{
    public string? UserName { get; set; }
    public string? Password { get; set; }
    public string? ConfirmPassword { get; set; }
}
2
  • Try changing body: JSON.stringify(formData) to body: formData Commented Feb 18, 2022 at 13:19
  • @phuzi Nope, still null Commented Feb 18, 2022 at 13:24

1 Answer 1

3

Do not set the content-type header.

   fetch("api/account/register", {
        method: "POST",
        body: formData
    }).then(response => response.json())
        .then(data => console.log(data));

or

 fetch("api/account/register", {
            method: "POST",
            headers: {'Content-Type': 'multipart/form-data'}
            body: formData
        }).then(response => response.json())
            .then(data => console.log(data));
Sign up to request clarification or add additional context in comments.

2 Comments

Ooh, good spot. The content-type application/json is not compatible with formData payload.
Thanks. I got method #1 to work, but method #2 didn't work for me - 400 error.

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.