javascript - 如何使用 fetch() javascript 方法将数据发布到 .NET Core Web API
问题描述
我正在尝试将数据从 React 前端发布到 .NET Core Web API 方法。我正在使用fetch()
javascript 方法发布。当我在 .NET 代码中设置断点来分析 viewModel 的值时,它的所有成员都为空。
我也尝试过传递一个简单的字符串而不是视图模型,但这也是空的。
我试过[FromBody]
在参数前面添加属性。
ContactForm.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);
}
ContactFormViewModel.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
};
并让您的客户端代码使用application/json
as content-type 发布 json 字符串。在服务器端接收值[FromBody]
:
[HttpPost("[action]")]
public ActionResult Contact([FromBody]ContactFormViewModel viewModel)
{
....
}
推荐阅读
- javascript - ngClass 和 onClick 不适用于 Div
- javascript - 如何在更新用户密码时验证旧密码?
- javascript - 按对象属性(对象数组)获取平均值的最有效方法
- android - MediaSession.SetMetadata 在蓝牙设备上不起作用
- arrays - Rails 如何从嵌套的 JSON 数据中提取数据
- python - Tkinter 窗口无故停止随机更新
- node.js - 使用 node.js 发布到 AWS Lambda 中的 ElasticSearch 索引,获得未经授权的响应
- php - 为什么我的 php-json-rpc 客户端不能与莱特币一起使用
- r - 光栅库不能在 r 中使用
- javascript - UI 未显示来自 react redux 工具包应用程序中数组项的更改