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; }
}
CodePudding user response:
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));