首页 > 解决方案 > 无法将 React App 连接到 .Net Core API,甚至没有调用 Post 方法

问题描述

所以我不知道为什么我不能从我的 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 方法。

谢谢!

标签: .netreactjsapiasp.net-core

解决方案


你可以尝试用[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

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


推荐阅读