【问题标题】:Can't connect React App to .Net Core API, Post method isnt even called无法将 React App 连接到 .Net Core API,甚至没有调用 Post 方法
【发布时间】:2020-06-06 08:57:38
【问题描述】:

所以我不知道为什么我不能从我的 React 应用程序向我的 .NET Core API 发出发布请求。获取请求工作正常。

我的反应代码:

 onCreateEmployee = () => {
let empInfo = {
  Id: this.refs.Id.value,
  Name: this.refs.Name.value,
  Location: this.refs.state.value,
  Salary: this.refs.Salary.value,
};

fetch("https://localhost:44371/api/Employee", {
  method: "POST",
  headers: { "Content-type": "application/json" },
  body: JSON.stringify(empInfo),
})
  .then((r) => r.json())
  .then((res) => {
    if (res)
      this.setState({ message: "New employee is created Successfully" });
  });

我的 .NET Core Post 方法:

public bool Post(Employee employee)
    {
        SqlConnection conn = new SqlConnection(@"server=DESKTOP-D0N7K1B\SQLEXPRESS; database=ReactAppDB; Integrated Security = True");
        string query = "insert into EmployeeInfo values(@Id,@Name,@Loc,@Sal)";
        SqlCommand cmd = new SqlCommand(query, conn);
        cmd.Parameters.Add(new SqlParameter("@Id", employee.Id));
        cmd.Parameters.Add(new SqlParameter("@Name", employee.Name));
        cmd.Parameters.Add(new SqlParameter("@Loc", employee.Location));
        cmd.Parameters.Add(new SqlParameter("@Sal", employee.Salary));
        conn.Open();
        int noOfRowsAffected = cmd.ExecuteNonQuery();
        conn.Close();
        return noOfRowsAffected > 0 ? true : false;
    }

Cors 已启用并按照成功获取请求的建议工作。 post 方法甚至没有被调用。

谢谢!

【问题讨论】:

    标签: .net reactjs api asp.net-core


    【解决方案1】:

    您使用的是什么版本的 Dot Net Core? 尝试在 Http Post 方法中添加[FromBody]

    public bool Post([FromBody] Employee employee)
    {
         // implementation
    }
    

    您也可以通过 Postman 发送同一个正文的相同请求,检查错误和错误代码。

    此外,您不应该将连接字符串放在您的方法函数中。 您可以查看Getting Started with EF Core 了解有关该主题的更多信息。

    【讨论】:

      【解决方案2】:

      您可以尝试使用[HttpPost] 属性来装饰您的方法。 (显式更好)

      另外,您想为请求对象指定[FromBody] 属性,如上面指定的@charbel。

      除此之外,您还可以尝试使用操作描述符查看您当前已注册的路由:

      public class YourController : Controller {
              private readonly IActionDescriptorCollectionProvider _provider;
      
              public YourController(IActionDescriptorCollectionProvider provider) {
                _provider = provider;
              }
      
              // You mentioned that you have a GET method that works as expected
              // You can add the code in there or you can create another route/method in that controller
              [HttpGet("routes")]
              public IActionResult GetRoutes() {
                  var routes = _provider.ActionDescriptors.Items.Select(x => new { 
                     Action = x.RouteValues["Action"], 
                     Controller = x.RouteValues["Controller"], 
                     Name = x?.AttributeRouteInfo?.Name, 
                     Template = x?.AttributeRouteInfo?.Template,
                     HttpMethods = x?.ActionConstraints?.OfType<HttpMethodActionConstraint>().FirstOrDefault()?.HttpMethods
                  }).ToList();
                  return Ok(routes);
              }
            }
      

      如果您希望始终有办法检查您的路由,我建议您添加一个中间件并创建一个以下列方式调用它的路由:https://gist.github.com/McKabue/b5caf25f9862b2488a9fa7898e22e86e

      或者添加一个swagger中间件:https://docs.microsoft.com/en-us/aspnet/core/tutorials/getting-started-with-swashbuckle?view=aspnetcore-3.1&tabs=visual-studio

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多