我正在尝试使用一个 POST 和一个 GET 请求制作简单的 Web 应用程序,但我无法找到任何解决方案,我非常绝望。我正在使用 .NET Core 和 React,一切正常,但是我无法让 POST 请求工作,我总是在控制台中收到 404。
来自 React 类的我的 POST 请求
handleSubmit(event){
superagent.post('api/WorkingTime/SaveWorkingTime')
.send({
Comment: this.state.Comment,
Date: this.state.Date,
Time: this.state.Time
})
.set('Accept', 'application/json')
.then(function(res) {
alert('Saved ' + JSON.stringify(res.body));
});
}
这是我想要接收 JSON 的 Controller (已更新 - 尝试返回 TimeLog 对象,仍然是 404)
[Produces("application/json")]
[Route("api/[controller]")]
public class WorkingTimeController : Controller
{
[HttpGet("[action]")]
public IEnumerable<string> WorkingTime()
{
return new string[] { "value1", "value2" };
}
[HttpPost]
public TimeLog SaveWorkingTime([FromBody] TimeLog time)
{
return time;
}
}
public class TimeLog
{
public string Comment { get; set; }
public string Date { get; set; }
public string Time { get; set; }
}
正如我之前提到的,当尝试获取WorkingTime() 时,我得到 200 OK
这个 GET 请求工作正常
fetch('api/WorkingTime/WorkingTime')
.then(response => response.json())
.then(data => {
this.setState({ msg: data });
});
这些是我需要发送的有效负载数据: Screenshot from console
谁能告诉我问题出在哪里?我们将不胜感激每一个帮助。
最佳答案
[HttpPost]
[Route("SaveWorkingTime")]
public IHttpActionResult SaveWorkingTime([FromBody] TimeLog time)
{
// Perform saving
return Ok(time);
}
添加了路线,以便我可以访问该 Post 方法。 api/WorkingTime/SaveWorkingTime
它可以工作。使用 Postman 进行测试。
引用:https://learn.microsoft.com/en-us/aspnet/core/fundamentals/routing#routing-basics
关于c# - POST 请求响应 404,而 GET 请求工作正常 .NET Core、React,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49489514/