POST请求以404响应,而GET请求正常工作.NET Core,React

时间:2018-03-26 10:41:52

标签: c# json reactjs api asp.net-core

我正在尝试使用一个POST和一个GET请求制作简单的Web应用程序,我无法找到任何解决方案而且我非常绝望。我正在使用带有React的.NET Core,一切正常,但我无法获得POST请求,我总是在控制台中获得404。

来自React类的MY 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

此请求正常

   fetch('api/WorkingTime/WorkingTime')
    .then(response => response.json())
    .then(data => {
        this.setState({ msg: data }); 
    });

这些是我需要发送的有效负载数据: Screenshot from console

任何人都可以告诉我问题出在哪里?我们将不胜感激。

1 个答案:

答案 0 :(得分:2)

[HttpPost]
[Route("SaveWorkingTime")]
public IHttpActionResult SaveWorkingTime([FromBody] TimeLog time)
{
    // Perform saving
    return Ok(time);
}

添加了路由,以便我可以访问该Post方法。 api/WorkingTime/SaveWorkingTime并且它有效。与Postman一起测试。

参考:https://docs.microsoft.com/en-us/aspnet/core/fundamentals/routing#routing-basics

相关问题