我在 Fetch POST to controller 中遇到问题,显示错误如 {"errors":{"":["Unexpected character encountered while parsing number: W. Path '', line 1, position 6."]},"title":"出现一个或多个验证错误。","status":400,"traceId":"0HLOGKVEBUTKL:00000007"}
。当我也调试时,在我的 Controller 中它没有传递给 Controller 。
这是我发布到的内容
我在客户端使用 ReactJs,在服务器端使用 Net Core。这是我的代码片段:
添加列表.js
fetch('api/SampleData/AddEmployee', {
method: 'POST',
headers: {
'Accept': 'application/json; charset=utf-8',
'Content-Type': 'application/json;charset=UTF-8'
},
body: data,
}).then((response) => response.json())
.then((responseJson) => {
console.log('Success:', JSON.stringify(responseJson));
this.props.history.push("/list-data");
})
.catch(error => console.error('Error:', error));
示例数据 Controller .cs
[HttpPost("[action]")]
public JsonResult AddEmployee(EmployeesViewModel employee)
{
}
starrup.cs
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
routes.MapRoute(
name: "api",
template: "api/{controller}/{action}/{id?}");
});
最佳答案
你不需要这个配置
routes.MapRoute(
name: "api",
template: "api/{controller}/{action}/{id?}");
而是像这样在你的 Controller 中使用路由
[Route("api/[controller]/[action]")]
public class YourController : Controller
关于javascript - 获取 POST ReactJs 到 Controller .Net Core,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57193853/