【发布时间】:2018-09-04 11:35:29
【问题描述】:
我正在尝试使用一个 POST 和一个 GET 请求制作简单的 Web 应用程序,但我找不到任何解决方案,我非常绝望。我正在使用带有 React 的 .NET Core,一切正常,但是我无法让 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 的控制器(已更新 - 尝试返回 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
谁能告诉我问题出在哪里?我们将不胜感激。
【问题讨论】:
-
SaveWorkingTime不应返回 void。 -
问题是我试图返回 TimeLog 对象,ActionResult,似乎没有任何帮助,仍然无法命中该方法内的断点
-
我注意到您在发布操作时返回 void。您是否尝试过退货?
-
从 url 中删除 SaveWorkingTime 或将 [Route("SaveWorkingTime")] 添加到您的操作中。
标签: c# json reactjs api asp.net-core