我正在尝试将数据从React前端发布到.NET Core Web API方法。我正在使用fetch()
javascript 方法发布。当我在 .NET 代码中设置断点以分析 viewModel 的值时,其所有成员均为 null。
我也尝试传递一个简单的字符串而不是视图模型,但这也是空的。
我尝试在参数前面添加[FromBody]
属性。
联系表格.js
onSubmit(e) {
e.preventDefault();
let data = {
viewModel: {
name: this.state.name,
serviceRequested: this.state.interest,
email: this.state.email,
phone: this.state.phone,
contactPreference: this.state.preference
}
};
fetch('api/Contact/Contact', {
method: "POST",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(response => {
response.text().then(function (text) {
alert(text);
});
});
}
联系人控制器.cs
private readonly string successMessage = "success";
private readonly string modelStateMessage = "Invalid input.";
[HttpPost("[action]")]
public ActionResult Contact(ContactFormViewModel viewModel)
{
if (ModelState.IsValid)
{
}
else
{
return Content(modelStateMessage);
}
return Content(successMessage);
}
联系人表单视图模型.cs
public class ContactFormViewModel {
[Required]
public string Name {get;set;}
public string ServiceRequested {get; set;}
[DataType(DataType.EmailAddress)]
public string Email {get;set;}
[DataType(DataType.PhoneNumber)]
public string Phone {get;set;}
public string ContactPreference {get;set;}
[StringLength(1000)]
public string Message {get;set;}
}
我希望数据填充视图模型属性,但它们都是空的。Firefox 的开发工具显示请求正在正文中传递 JSON 参数。
从 修改代码:
let data = {
viewModel: {
name: this.state.name,
serviceRequested: this.state.interest,
email: this.state.email,
phone: this.state.phone,
contactPreference: this.state.preference
}
};
自:
let data = {
name: this.state.name,
serviceRequested: this.state.interest,
email: this.state.email,
phone: this.state.phone,
contactPreference: this.state.preference
};
并保留客户端代码以发布 json 字符串,application/json
作为内容类型。使用[FromBody]
在服务器端接收值:
[HttpPost("[action]")]
public ActionResult Contact([FromBody]ContactFormViewModel viewModel)
{
....
}
我总是用来使该方法成为静态和异步的,您可以相应地修改,即在不需要的情况下删除静态和异步。如果您有任何疑问,请回复
下面是代码:
static async post(URL, body) {
debugger;
const response = await fetch(`${API_URL_PREFIX}/api/${url}`, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
Pragma: 'no-cache',
},
body: JSON.stringify(body),
credentials: 'include',
mode: 'cors',
})
return response.ok;
}