.net - 无法将 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 方法。
谢谢!
解决方案
你可以尝试用[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
推荐阅读
- typescript - 运算符“+”不能应用于类型“T”和“T”。在打字稿中
- java - Selenium Serenity 屏幕截图和电影延迟并挂起执行
- angular - 打破组件和模板之间的绑定
- c - 警告:[-Wformat=] 和 strcmp() 在 C 中没有比较
- sql-server - 动态 SQL Where 条件,在 Powershell 脚本中
- html - 如何在 Lightbox 中使用 WebP 图片?
- javascript - 如何使用css将邮票文本放入发票中
- flutter - 颤振:如何更改网格视图内的背景颜色?
- python - 将列值设置为熊猫中组的平均值
- c++ - 是否有解决方案可以从“无效转换 int* 到 int”C++ 中逃脱?